Home Forums General Issues How to count single time post views ?


How to count single time post views ?

  • Hi everyone, I have a custom counter that shows post views. Everything works perfectly, however, if the same user (regardless if logged in or logged out) reloads the page 10 times, then the counter will add 10 views.

    Is it possible to add a single view for each user?
    A bit how it works for youtube for example.

    I am using the following code:
    Located in Header.php

    $count = get_field('views');			  
    update_field('views', number_format($count,0,",","."));
  • You would need to record each user’s views separately. For example a field for each user on every post that records the views for that user. Or you would need to have a field in usermeta for each user that records all of the posts viewed by that user.

    Then you would need to check this field to see if a the view should be added before adding it.

    Finally you would need to aggregate all of these values to show the total page views.

    As an example, let’s say that I wanted to record this for each post. I would create a WP custom field that stores and array of user IDs that have viewed the page. When the page is loaded I would check this array to see if this user has viewed it.

    $views = get_post_meta($post->ID, 'post_views', false);
    if (empty($views)) {
      $views = array();
    $user_id = 0;
    if (is_user_logged_in()) {
      $user_id = get_current_user_id();
    if (empty($views[$user_id])) {
      $views[$user_id] = $user_id;
    update_post_meta($post->ID, 'post_views', $views);
    $total_views = count($views);
Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.