Updating article hits when using Joomla cache

Enable cache, and disable hits
When you enable caching in Joomla, article hits do not increase when cached pages are served. This is unfortunately a limitation of the caching system in Joomla, there is not “toggle switch” to enable this feature.

Hits not always accurate, but sometimes needed
For those users needing this feature, it’s usually recommended that they instead switch to a more accurate tracking system, like Google Analytics. This though is an alternative, and doesn’t actually present a solution to the problem at hand. Even though not 100% accurate, sometimes article hits are necessary, such as the scenario when you need to order articles based upon their popularity.

We created a solution
The article that you’re reading right now is within InMotion Hosting’s Support Center, and is served using Joomla. We have enabled caching in Joomla, and ourselves needed the hits on articles to increase. In this tutorial, we will outline the steps we’ve taken to have Joomla increase article hits event when a cached page is served.

  1. Disable article hits

    I know it sounds funny, but the first step in this entire process is to disable article hits. The solution we are implementing will use ajax to increase article hits. We don’t want Joomla to increase hits at the same time our ajax call is increasing hits, this would result in double hits.

    Edit the following file and add the code highlighted in red below:

    components/com_content/models/article.php

    public function hit($pk = 0)   {     return true;     $input = JFactory::getApplication()->input;     $hitcount = $input->getInt('hitcount', 1);      if ($hitcount)     {       $pk = (!empty($pk)) ? $pk : (int) $this->getState('article.id');        $table = JTable::getInstance('Content', 'JTable');       $table->load($pk);       $table->hit($pk);     }      return true;   }

    Core file change!
    This step edits a core file, which is not recommended. You can skip this step, however this will result in hits increasing by 2 (instead of 1) when cache is not used to server a page.

  2. Enclose your hit count within a span tag

    After using ajax to make a call to increase article hits, we will update the current hit counter on the page so that it is accurate. We will use javascript for this, and javascript needs to know where on the page the hits are showing. We label the article hit counts by wrapping it within a span tag.

    Create a language override and add the changes highlighted in red:

    Language Constant: COM_CONTENT_ARTICLE_HITS
    Text Hits: <span id=”article_hits”>%s</span>
  3. Add the ajax calls to your articles

    Now it’s time to add the ajax calls to our articles. It’s this ajax call that makes a request to increase article hits, and will run regardless if the page is being served via cache or not. Edit the following file and add the code highlighted in red at the end of the file:

    components/com_content/views/article/tmpl/default.php

      <?php if (!empty($this->item->pagination) && $this->item->pagination && $this->item->paginationposition && $this->item->paginationrelative) :   echo $this->item->pagination; ?>   <?php endif; ?>   <?php echo $this->item->event->afterDisplayContent; ?> </div>  <script type='text/javascript'>         jQuery.post(                 '<?php echo JURI::base(); ?>includes/increase_hits.php',                 {option:'com_content',view:'article',id:'<?php echo $this->item->id; ?>'},                 function(data,status){jQuery('#article_hits').html(data);},'text'         ); </script>

    Core file change!
    This step edits a core file, which is not recommended. You should instead add this code to an override.

  4. Create increase_hits.php

    Create the following file. This is the php script that our ajax call will interact with.

    includes/increase_hits.php

    <?php  /**  *  Use this script to update article hits when caching is enabled  *  Setup guide can be found here: https://www.inmotionhosting.com/support/edu/joomla-3/increase-hits-cache  */   if (  $_POST['option'] == "com_content"       && $_POST['view'] == "article"       && is_numeric($_POST['id'])) {   // connect to the database   include_once("../configuration.php");   $cg = new JConfig;   $con = mysqli_connect($cg->host,$cg->user,$cg->password,$cg->db);   if (mysqli_connect_errno())     die('n/a');    // increase hits   $query = "  UPDATE  `" . $cg->dbprefix . "content`               SET     `hits` = `hits` + 1               WHERE   `id` = " . $_POST['id'] . "               LIMIT 1;   ";   mysqli_query($con,$query);    // grab the new hit count   $query = "  SELECT  `hits`               FROM    `" . $cg->dbprefix . "content`               WHERE   `id` = " . $_POST['id'] . "               LIMIT 1;   ";   $new_hits = mysqli_fetch_assoc(mysqli_query($con,$query));    // close the connection to the database   mysqli_close($con);    echo $new_hits['hits']; }  ?>

And that’s it! It’s the same approach we’ve used for our own Joomla site. If you have any problems getting this to work, feel free to post a comment below. Alternatively, post a comment too if you have another method users can implement to increase hits when cache is being used.

Thanks!
A special thanks to Pankaj with joomlart.com for the encouragement to write this article.