Quantcast
Channel: Crunchify
Viewing all articles
Browse latest Browse all 1037

WordPress: How to Track Post Views without a Plugin using Post Meta

$
0
0

WordPress Crunchify Tag Cloud WordPress: How to Track Post Views without a Plugin using Post Meta

If you want to keep real-time track of your WordPress post views / hit by user then you can use this code. Below code snippet/plugin will gives stats for each post.

Step1: Put this into functions.php file.

function getCrunchifyPostViews($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 setCrunchifyPostViews($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_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);

Step 2.

Place this snippet below “setPostViews” within the single.php inside the loop.

<?php
          setCrunchifyPostViews(get_the_ID());
?>

Another must read:

Step 3.

Place this snippet below within the template where you would like to display the number of views.

<?php
          echo getCrunchifyPostViews(get_the_ID());
?>

The post WordPress: How to Track Post Views without a Plugin using Post Meta appeared first on Crunchify.


Viewing all articles
Browse latest Browse all 1037

Trending Articles