How to show popular posts by views in WordPress

This is a bit cunning snippet. However, if you want to showcase your favorite posts without any plugin installation then this is the best way to do so. Just follow this snippet.
Paste the following to the function.php file in your child theme.

function wps_count_post_views() {

    if( is_single() ) {

        global $post;

        $counts = get_post_meta( $post->ID, 'my_post_counts', true );

        if( $counts == '' ) {

            update_post_meta( $post->ID, 'my_post_counts', '1' );   

        } else {

            $count_no = intval( $counts );
            update_post_meta( $post->ID, 'my_post_counts', ++$count_no );

        }
    }
}

add_action( 'wp_head', 'wps_count_post_views' );

In this function we are first, checking if the existing is a single post. Then in a $counts variable, we are extracting the post meta from the specific post through ID. Then on an empty $counts variable, we are updating the post meta of the specific post through ID.

Now Paste this code into your template where you want to display the posts.

// passing the post detail array

$favourite_posts_args = array(
    'posts_per_page' => 3,
    'meta_key'       => 'my_post_counts',
    'orderby'        => 'meta_value_num',
    'order'          => 'DESC'
);

$favourite_posts_loop = new WP_Query( $popular_posts_args );

while( $favourite_posts_loop->have_posts() ){

    $favourite_posts_loop->the_post();   

}

wp_reset_query();

Here we are passing an argument where we are adding the details related to the post and how much to display on a single page.
With the help of WP_Query and while loop we are displaying the posts on the page and resetting the query through WP_reset_query.

Leave a Comment

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

Scroll to Top