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
    TextHits: <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: http://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.

Joomla Community - Google Hangout #3

Continued Education in Course Joomla 3
You are viewing Section 15: Updating article hits when using Joomla cache
Section 14: DocBlocks - Documentation headers in Joomla
Section 16: Jimport
Did you find this article helpful?

We value your feedback!

Why was this article not helpful? (Check all that apply)
The article is too difficult or too technical to follow.
There is a step or detail missing from the instructions.
The information is incorrect or out-of-date.
It does not resolve the question/problem I have.
How did you find this article?
Please tell us how we can improve this article:
Email Address
Name

new! - Enter your name and email address above and we will post your feedback in the comments on this page!

Related Questions

Here are a few questions related to this article that our customers have asked:
Ooops! It looks like there are no questions about this page.
Would you like to ask a question about this page? If so, click the button below!
Ask a Question

Joomla Community Google+ Hangout #3

June 3rd, 2014

Thank you @RustyJoomla for letting me speak on the Joomla Community Google+ Hangout!

Click here to watch!

n/a Points
2014-06-13 5:06 am

Great, thank you for the tips. Would this work for Joomla 2.5 and how to have the same for K2 items ?

Staff
9,384 Points
2014-06-13 7:52 am
It has not been tested but in theory it should work just fine in Joomla 2.5. Unfortunately, we are not familiar with K2.

Post a Comment

Name:
Email Address:
Phone Number:
Comment:
Submit

Please note: Your name and comment will be displayed, but we will not show your email address.

2 Questions & Comments

Post a comment

Back to first comment | top

Need more Help?

Search

Ask the Community!

Get help with your questions from our community of like-minded hosting users and InMotion Hosting Staff.

Current Customers

Chat: Click to Chat Now E-mail: support@InMotionHosting.com
Call: 888-321-HOST (4678) Ticket: Submit a Support Ticket

Not a Customer?

Get web hosting from a company that is here to help. Sign up today!