0 %

Show view count of a post on wordpress

Show view count of a post on wordpress

You can simply do it without a plugin.

To count the post views, the first thing you have to do is to add the following code to your WordPress Theme functions.php

<?php
/*
 * Set post views count using post meta//functions.php
 */
function customSetPostViews($postID) {
    $countKey = 'post_views_count';
    $count = get_post_meta($postID, $countKey, true);
    if($count==''){
        $count = 0;
        delete_post_meta($postID, $countKey);
        add_post_meta($postID, $countKey, '1');
    }else{
        $count++;
        update_post_meta($postID, $countKey, $count);
    }
}
?>

And now we will call this function in the single.php to update the count value in the Database.

<?php 
    customSetPostViews(get_the_ID());//single.php
?>

Now in the same single.php file if we want to show the post view count, we can use this code:

<?php
    $post_views_count = get_post_meta( get_the_ID(), 'post_views_count', true );
    // Check if the custom field has a value.
    if ( ! empty( $post_views_count ) ) {
        echo $post_views_count;
    }
?>

Now to show all the popular post in the descending order by post view count. use this code:

<?php//popular post query
    query_posts('meta_key=post_views_count&posts_per_page=5&orderby=meta_value_num&
    order=DESC');
    if (have_posts()) : while (have_posts()) : the_post();
?>
    <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php
    endwhile; endif;
    wp_reset_query();
?>

Happy Coding

Việt Lâm Coder

Việt Lâm Coder

Senior Fullstack & System Architect

Cần hỗ trợ website? Gọi / Zalo 0944.71.4545.

Trao đổi về dự án của bạn!

VietLamCoder CMS — Nền Tảng Quản Trị Flat-File Siêu Tốc LamWeb.com.vn — Hệ Sinh Thái Thiết Kế Web & Kho Giao Diện 2026