Search code examples
phpwordpresswordpress-themingcountercustom-wordpress-pages

Wordpress how to add a page counter


I'm using a custom number field (generated by Jet Engine plugin) to track the number of times a page was loaded.

On my functions.php file I am using this code:

$count = get_post_meta("706", 'counter', true );
if(!is_admin() && !current_user_can('administrator')){
$count++;
update_post_meta("706", 'counter', $count );
}

'counter' is the field name.

I am using the if(!is_admin) so it will not count my back end testings.

My main issue is that the counter is not consistent, and although for most of the times it counts in steps of 1, it sometimes skips and count 2, 3 or 4 on a single page load.

This is a link to my test page:

https://oferziv.com/ofer/test/test3/

What am I missing here?


Solution

  • Like i said, i always use the wp_head action hook and it works seamlessly fine!

    function my_counter_function()
    {
      if (is_admin() || current_user_can('activate_plugins')) return;
    
      $counter = get_post_meta("706", 'counter', true);
    
      if (empty($counter)) {
        $counter = 1;
        update_post_meta("706", 'counter', $counter);
      } else {
        $counter++;
        update_post_meta("706", 'counter', $counter);
      }
    }
    
    add_action('wp_head', 'my_counter_function'); // This is the action hook i was talking about!