1

how to show post views on single.php? What I tried:

function getPostViews($postID){
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
        return "0 View";
    }
    return $count.' Views';
}
function setPostViews($postID) {
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
    }else{
        $count++;
        update_post_meta($postID, $count_key, $count);
    }
}
// Remove issues with prefetching adding extra views
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);

It works well and counts the views but it counts views every time even a single viewer refreshes the page again and again. I want to play with session cookies but don't know how to achieve that. What I tried to achieve that is I replaced the second function with the below function:

function setPostViews($postID) {
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
$count = 0;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
}else{

/*
* Check the cookie is exist or not.
* If not the set cookie for some time interval and
* increase the count
*/
if(!isset($_COOKIE['wpai_visited_ip']))

$count++;
update_post_meta($postID, $count_key, $count);

// Get IP address
$visit_ip_addr = $_SERVER['REMOTE_ADDR'];

// Set the cookie
setcookie('wpai_visited_ip', $visit_ip_addr, time()+ (60 * 1));

}
}

But it doesn't work, I got the following error:

Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\portfolio\wp-includes\class.wp-styles.php:287) in C:\xampp\htdocs\portfolio\wp-content\themes\portfolio\breadcrumb.php on line 152

Please help if anyone can do it for me. I just need to increase views counter when a new user views my post in a single session.

  • Can you post the full version of breadcrumb.php and note which line is 152? – Tom Jan 12 at 13:11
  • This is line 152: setcookie('wpai_visited_ip', $visit_ip_addr, time()+ (60 * 1)); – Farhan Ali Jan 12 at 13:13
  • Great, thanks for confirming that. What triggers the function setPostViews - is it set to hook in somewhere? For example: add_action('init','setPostViews'); – Tom Jan 12 at 13:25
  • I am not confirmed about that, I think this line executes the function: remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0); I used this line to call this function on my single.php: <?php echo getPostViews(get_the_ID()); ?> And I added this line in while loop to set post view: if ( !is_user_logged_in() ) { setPostViews(get_the_ID()); } – Farhan Ali Jan 12 at 13:55
2

Your implementation of the getPostViews function looks fine, and I don't see an issue having that inside your single.php or breadcrumbs.php.

However, I would move both functions into your functions.php (more info here) and rather than calling setPostViews inside single/breadcrumbs.php, I would attach it to a WordPress action.

<?php
//...inside your functions.php...

add_action( 'init', 'fa_setpostviews' );
function fa_setpostviews() {
    global $post;

    // Do not continue if we do not have a post ID
    if ( ! isset( $post->ID ) ) {
        return;
    }

    // Do not continue if the user is not logged in
    if ( ! is_user_logged_in() ) {
        return;
    }

    // Make sure the user is on a single post.
    if ( ! is_single() ) {
        return;
    }

    /*
     * Note! The above if statements could be combined into one.
     */

    $postID = $post->ID;

    $count_key = 'post_views_count';
    $count     = get_post_meta( $postID, $count_key, true );
    if ( $count == '' ) {
        $count = 0;
        delete_post_meta( $postID, $count_key );
        add_post_meta( $postID, $count_key, '0' );
    } else {
        if ( ! isset( $_COOKIE['wpai_visited_ip'] ) ) {
            $count ++;
        }

        update_post_meta( $postID, $count_key, $count );

        $visit_ip_addr = $_SERVER['REMOTE_ADDR'];
        setcookie( 'wpai_visited_ip', $visit_ip_addr, time() + ( 60 * 1 ) );

    }
}

The above function checks if the user is logged in, if the user is on a single post page and then executes the count script as before.

Note: This is on the init hook, which may not be the best hook for your uses. Init is called multiple times and you may want to hook into wp instead. See more here on hooks and actions: https://codex.wordpress.org/Plugin_API/Action_Reference

  • 1
    It worked. Really thanks a lot man!. – Farhan Ali Jan 12 at 20:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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