skip to Main Content

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?

2

Answers


  1. Usually, you’ll want to wrap everything inside a proper hook, like so:

    // Runs on every page request after we have a valid user.
    
    add_action('init', function () {
    
        // Return early if we're in the backend...
    
        if (is_admin()) {
    
            return;
        }
    
        // ...or the current user has admin capabilities 
    
        if (current_user_can('activate_plugins')) {
    
            return;
        }
    
        // Otherwise, update counter
    
        $count = get_post_meta("706", 'counter', true );
        $count++;
        
        update_post_meta("706", 'counter', $count );
    });
    

    About how to use hooks, see:

    For checking user privileges, see:

    Login or Signup to reply.
  2. 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!
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search