I have a requirement where I want to show the total number of hits that a user's items have been read. For example, if they have ten K2 items, each have been read 10 times, then I want to show the total number (in this case 100) of hits that users total items have been read.

K2 has a variable, which I can echo for each of the items:

<?php echo $item->hits; ?>

But I need a way to add all of the authors items hits up.

** Update **

So I'm thinking, could this be done using a SQL query? Something similar to:

SELECT count('hits') FROM #__k2_items WHERE authorid='id';
  • a small change in your query must be there: instead of count take sum('hits') . check with this if it works
    – Liz.
    Oct 19, 2016 at 13:28

1 Answer 1


This should be what you need.

$db = JFactory::getDbo();

$query = $db->getQuery(true);
      ->where($db->qn('created_by') . ' = ' . $db->q($this->user->id));

$results = $db->loadObjectList();

$sum = 0;
foreach ($results as $key => $val)
    $sum+= $val->hits;

echo number_format($sum);

Simple database query that returns that hits for all articles created by the author of the current article being views.

It that adds each of the values in a foreach loop and displays the result.

Hope this helps :)

  • Just tried that, but it's returning 0 when echoing $sum Oct 19, 2016 at 12:52
  • Did you use the updated code? I ended up editing my answer quite a lot when I submitted it. I'm not sure where you're adding the code, by I tried in components\com_k2\templates\default\item.php with the code in my answer and everything seems to be working fine.
    – Lodder
    Oct 19, 2016 at 13:01
  • It should be noted that this code should be written as a plugin and NOT added to your component's user.php file or module's authors.php file. This prevents SQL from running in your templates. If you would rather add code to your templates, there is another way using K2's reference variables, similar to your first suggestion. Oct 19, 2016 at 14:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.