How to Count Post Views in WordPress

You are a webmaster and you want to keep track of your posts or you want to know if your website has anyone interacting with it? The simplest way is to integrate the article with the view checking feature, so you will easily know the number of views on each blog post on your WordPress website. Using this feature, readers can determine the quality of the article thanks to the number of views and they will feel more secure and want to click to the blog post to read when the number of views is higher than the others. So, in this article, I will guide you how to count post views in WordPress with or without using plugins. Now, let’s take a look.

How to count post views in WordPress without using plugins

1. First and foremost, go to the Functions.php file of the currently used theme of WordPress. Then copy the code below and paste it before the closing tag?> of the Functions.php file.

function gt_get_post_view() {
    $count = get_post_meta( get_the_ID(), 'post_views_count', true );
    return "$count views";
}
function gt_set_post_view() {
    $key = 'post_views_count';
    $post_id = get_the_ID();
    $count = (int) get_post_meta( $post_id, $key, true );
    $count++;
    update_post_meta( $post_id, $key, $count );
}
function gt_posts_column_views( $columns ) {
    $columns['post_views'] = 'Views';
    return $columns;
}
function gt_posts_custom_column_views( $column ) {
    if ( $column === 'post_views') {
        echo gt_get_post_view();
    }
}
add_filter( 'manage_posts_columns', 'gt_posts_column_views' );
add_action( 'manage_posts_custom_column', 'gt_posts_custom_column_views' );

2. Then, copy the code below and paste it into single.php file in the while loop.

Leave a Comment

Your email address will not be published. Required fields are marked *