I am using CCK and views to create a particular view of my CCK content-type. The layout of this view has been modified by putting my HTML and PHP tags in a file that is named: node-view-custom_view_name.tpl.php.

This is working great (I love CCK and custom views in Drupal!) but I have a problem with the counts provided by the statistics module. When I hit a page containing a custom view(/property/16), the count is not incremented. Only when a node is viewed in stadard node structure (/node/16) the page count is registered.

This gives me the wrong (count remains 0) results in the Most popular blocks I have created because the standard node URL (node/16) is never beeing hit.

How can the custom view of the node let the counter increment when this is viewed by a visitor?
Am I missing something here?

Comments

dawehner’s picture

i think this is not a problem of your custom tpl, the problem is that you are not on node/$NID

see this code of statistics module

<?php    
    if ((arg(0) == 'node') && is_numeric(arg(1)) && arg(2) == '') {
      // A node has been viewed, so update the node's counters.
      db_query('UPDATE {node_counter} SET daycount = daycount + 1, totalcount = totalcount + 1, timestamp = %d WHERE nid = %d', time(), arg(1));
      // If we affected 0 rows, this is the first time viewing the node.
      if (!db_affected_rows()) {
        // We must create a new row to store counters for the new node.
        db_query('INSERT INTO {node_counter} (nid, daycount, totalcount, timestamp) VALUES (%d, 1, 1, %d)', arg(1), time());
      }
    }
?<

So you could for example execute the same code for your view

Erco’s picture

Aggree with dereine.
If you want to update your counter, you can add php code in the footer of your view.

Edit your view.
Ensure that node->nid is defined in the "field section' of your view. (is necessary check the option not to display it) and click on the footer option.

Insert the following php code:
- note the print_r commented line: use it to check that you retrieve the right nid (in my case it is '$res[0]->node_users_nid')
- It's about the same code as mentioned by dereine, except that we by pass the "node check" of the statistic module, and we retreive node->nid from the view.
- You may add more checks if you don't want to count administrator access or other ($user->gid)

global $user, $recent_activity;
$view = views_get_current_view();
$res = $view->result;
//print_r($res);


  if (variable_get('statistics_count_content_views', 0)) {
    // We are counting content views.

      // A node has been viewed, so update the node's counters.
      db_query('UPDATE {node_counter} SET daycount = daycount + 1, totalcount = totalcount + 1, timestamp = %d WHERE nid = %d', time(), $res[0]->node_users_nid);
      // If we affected 0 rows, this is the first time viewing the node.
      if (!db_affected_rows()) {
        // We must create a new row to store counters for the new node.
        db_query('INSERT INTO {node_counter} (nid, daycount, totalcount, timestamp) VALUES (%d, 1, 1, %d)', $res[0]->node_users_nid, time());
      }
  
  }

merlinofchaos’s picture

Status: Active » Fixed

Though better code to state that the user touched a node, copied directly from node_show() so it is what Drupal uses:

  node_tag_new($node->nid);

Put this either in your template or in PHP code in the header or footer of the view. Make sure you extract $node->nid from the URL if using header or footer since it won't have a $node variable available.

Erco’s picture

Yes, indeed I tried to implement node_tag_new() first.

But in my case it did not work.

The history table was updated.
But the node_count table was not updated by the statistic module.

My case was: Several fields of a node, built through views and displayed in a Panel (itself overrinding the node url)

Br,
Erco

dawehner’s picture

as you see in http://api.drupal.org/api/function/statistics_exit/6 there are two different tables

so node_tag_new cannot work :)

perhaps statistics module needs a better api

dglerum’s picture

Erco and others, thank you very much for your solutions.

@Erco: I tried to add this code to the footer of my custom view. Uncommenting the result line gives me the correct NodeID that is viewed at that time. However the "Total Views"-counter does not increment when I visit the view as a user (registered or anonymous give same results). PHP code is selected as input in view-footer obviously...

I am also unable to add the field separately as this view is configured as "Row Style = node", so no fields can be added or changed. Does this mean all fields are there to work with?

edit: this code did the job (small mod on the snipped from dereine). I just needed to change the argument arg(0) according to my defined path setting (arg(0) == 'property') as I have a custom URL defined in the view.

Great stuff guys... thanks you all.


<?php    
    if ((arg(0) == 'property') && is_numeric(arg(1)) && arg(2) == '') {
      // A node has been viewed, so update the node's counters.
      db_query('UPDATE {node_counter} SET daycount = daycount + 1, totalcount = totalcount + 1, timestamp = %d WHERE nid = %d', time(), arg(1));
      // If we affected 0 rows, this is the first time viewing the node.
      if (!db_affected_rows()) {
        // We must create a new row to store counters for the new node.
        db_query('INSERT INTO {node_counter} (nid, daycount, totalcount, timestamp) VALUES (%d, 1, 1, %d)', arg(1), time());
      }
    }
?>


Regards
Davy

Status: Fixed » Closed (fixed)

Automatically closed -- issue fixed for 2 weeks with no activity.

cimo’s picture

Hi
I need a little help, I am in the same situation but can t get out of it. I tried the different codes but none work.
I placed the code in the view s footer, added the nid field and, of course, the view is overriden, any idea? I can t read the code so I am a bit lost.
Thanks
Simone

here is the code I am using
[code]

global $user, $recent_activity;
$view = views_get_current_view();
$res = $view->result;
print_r($res[0]->node_users_nid);


  if (variable_get('statistics_count_content_views', 0)) {
    // We are counting content views.

      // A node has been viewed, so update the node's counters.
      db_query('UPDATE {node_counter} SET daycount = daycount + 1, totalcount = totalcount + 1, timestamp = %d WHERE nid = %d', time(), $res[0]->node_users_nid);
      // If we affected 0 rows, this is the first time viewing the node.
      if (!db_affected_rows()) {
        // We must create a new row to store counters for the new node.
        db_query('INSERT INTO {node_counter} (nid, daycount, totalcount, timestamp) VALUES (%d, 1, 1, %d)', $res[0]->node_users_nid, time());
      }
 
  }

[/code]

cimo’s picture

I j¡ve just realized that my situation is a bit different.
First of all I was trying to put the code in a view template,, not in a the view-node override, so no surprise it was no working.
My problem is that the view count field of all my view doesn report any visit, although the node are not overriden.
What am I missing?
thanks
Simone

carvalhar’s picture

hi,

Does variable_get('statistics_count_content_views', 0) makes sense outside statistics module? I mean...in my case it didn't change nothing. Is always 0...

After updating total count, if i set it to 1, it means only for the user logged, or it's a system variable?

thanks

carvalhar’s picture

Status: Closed (fixed) » Active

From 2009 to today, is there a better way to do this?
thanks

dawehner’s picture

Status: Active » Fixed

Nope there is not. Perhaps you could use rules to do this, but this might be not that fast.

carvalhar’s picture

hi,

I think I found a better way to do this, because #2 statistics_count_content_views variables is always 0 for me. I'm checking the history table if the user viewed the node today with this:

$view = views_get_current_view();
$res = $view->result;
$last_time = format_date(node_last_viewed($res[0]->nid), 'custom', $format = 'd/m/Y');
$date_today = format_date(mktime(), 'custom', $format = 'd/m/Y');
//echo $last_time . " " . $date_today;
if ((arg(1) != $res[0]->nid) && (node_last_viewed($res[0]->nid) == 0 || $last_time != $date_today)){	
	node_tag_new($res[0]->nid);
	$exists = db_result(db_query("SELECT COUNT(0) FROM node_counter where nid =". $res[0]->nid));
	if ($exists > 0) {
		$result = db_query('UPDATE node_counter SET daycount = daycount + 1, totalcount = totalcount + 1, timestamp = '.time().' WHERE nid = ' . $res[0]->nid);
	}
	else {
		db_query('INSERT INTO node_counter (nid, daycount, totalcount, timestamp) VALUES ('.$res[0]->nid.', 1, 1, '.time().')');
	}
} 

Status: Fixed » Closed (fixed)

Automatically closed -- issue fixed for 2 weeks with no activity.

dean.humphreys’s picture

Hi,

I know this issue is closed but if anyone is looking for the code to do this in Drupal 7, here it is:

global $user, $recent_activity;
$view = views_get_current_view();
$res = $view->result;
//print_r($res);

 if (variable_get('statistics_count_content_views', 0)) {
	//Insert a new row or update the original one
	db_merge('node_counter')
		->key(array('nid' => $res[0]->nid))
		->expression('daycount', 'daycount + :daycount', array(':daycount' => 1))
		->expression('totalcount', 'totalcount + :totalcount', array(':totalcount' => 1))
		->fields(array(
			'timestamp' => time())
		)
		->execute();
  
  }

hbrrm010’s picture

Version: 6.x-2.5 » 7.x-3.1

To enable node views count I needed two steps:
1. enable statistics module
2. go to admin->configuration->statistics and there enable the "Content viewing counter settings". Just check the box saying "count conntent views".
Hope this helps someone

rvdtuin’s picture

I would like to try these solutions, but where (which file) do I put the php code?
thanks

rvdtuin’s picture

I had the php code in the view footer and it worked fine.
After updating views to views 7.x-3.6 I get this at the and of a displayed item (node):

global $user, $recent_activity
;$view = views_get_current_view();
$res = $view->result;
if (variable_get('statistics_count_content_views', 0)) {
db_merge('node_counter')
->key(array('nid' => $res[0]->nid))
->expression('daycount', 'daycount + :daycount', array(':daycount' => 1))
->expression('totalcount', 'totalcount + :totalcount', array(':totalcount' => 1))
->fields(array(
'timestamp' => time())
)
->execute();
}
?>

Does anyone know what to do?

emcniece’s picture

@rvdtuin - wrap your code in <?php ... ?> tags. Are you missing a <?php at the beginning of the snippet?

fabiannavarro’s picture

Issue summary: View changes

#15
This code works great, which is the code that distinguishes different types of content in a view?
Thanks for any response, Fabian.

ñull’s picture

My nodes are shown in a Bootstrap Accordion. How do I increment view count when an accordion is opened?

ñull’s picture

Status: Closed (fixed) » Needs work
JacksonBison’s picture

Can't seem to get this working - I get the following error:

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'nid' cannot be null: INSERT INTO {node_counter} (nid, timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1); Array ( [:db_insert_placeholder_0] => [:db_insert_placeholder_1] => 1463292421 ) in __lambda_func() (line 16 of \sites\all\modules\views_php\plugins\views\views_php_handler_area.inc(39) : runtime-created function).

rimibhagat’s picture

#16 hbrrm010's steps worked with a condition that the counter is incremented only when cron is run.
If anyone doesn't want the code step they can try it by customizing cron run as needed.

MustangGB’s picture

Status: Needs work » Fixed

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.