How can I display the Most Viewed posts in WordPress?

✔ Recommended Answer

Open the functions.php file of the activated theme and add the following code.

setPostViews() function add or update the post meta with post_views_count meta key.

/* * Set post views count using post meta */function setPostViews($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, '0');    }else{        $count++;        update_post_meta($postID, $countKey, $count);    }}

single.php File

Open the single.php file from activated theme directory and place the setPostViews() function inside the loop.


Display the Most Viewed Posts

The following query will fetch the posts based on the post_views_count meta key value. Place the following code in the sidebar or where you want to display the most popular posts list.

<?phpquery_posts('meta_key=post_views_count&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><?phpendwhile; endif;wp_reset_query();?>


Answered By: Ivan Barayev

Method #2

To display the most viewed posts in WordPress, you'll need to use a plugin that tracks post views, such as "Post Views Counter" or "WP Postviews". Once you've installed and activated the plugin, you can use the following code to display the most viewed posts:

<?php $args = array( 'post_type' => 'post', 'posts_per_page' => 10, 'meta_key' => 'post_views_count', 'orderby' => 'meta_value_num', 'order' => 'DESC' ); $query = new WP_Query($args); if ($query->have_posts()) : while ($query->have_posts()) : $query->the_post(); // Your post loop code here endwhile; endif; wp_reset_postdata(); ?>

This code uses the WP_Query class to query posts from the post post type, and orders them by the post_views_count meta value (which is provided by the post views tracking plugin). You can adjust the posts_per_page argument to change the number of posts displayed, and modify the post loop code to display the post content in the way you prefer.

Note that some post views tracking plugins may use a different meta key for tracking views, so make sure to check the documentation for your chosen plugin to ensure you're using the correct key.


Most Popular

Remove Unicode Zero Width Space PHP

PhpStorm, return value is expected to be 'A', 'object' returned

Laravel file upload returns forbidden 403, file permission is 700 not 755