Blog for web designers

List of popular post without plugin in wordpress

We have lots of plugin that helps to get the list of popular post in wordpress. But lets now imagine that we can do it without any plugin. List of popular post without plugin in wordpress of your website, copy the below code into your function.php

function wordpress_set_post_views($postID) {
    $count_key = 'wordpress_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);

After that lets add some snippets to to the single post to track the exact post views.

wordpress_set_post_views(get_the_ID());

It was too easy. Now lets take a step to list the popular post ordering by meta value.

Wp query to list the post

>?php 
$popularpost = new WP_Query( array( 'posts_per_page' => 4, 'meta_key' => 'wordpress_post_views_count', 'orderby' => 'meta_value_num', 'order' => 'DESC'  ) );
while ( $popularpost->have_posts() ) : $popularpost->the_post();

the_title();

endwhile;
?<

Santosh Shah

My name is Santosh Shah and blogs at santosh-shah.com


Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.