How to Display Most Popular Posts in WordPress

The following steps will display a list of your Most Popular Posts with thumbnail images in the sidebar of your WordPress-powered website. The list will be consist of five titles right next to their corresponding images.

1. Add the following lines of code to the functions.php file:

// Set image sizes
add_theme_support('post-thumbnails');
if ( function_exists( 'add_theme_support' ) ) {
add_theme_support( 'post-thumbnails' );
set_post_thumbnail_size( 50, 50, array( 'center', 'center') );
add_image_size( 'excerpt-image', 60, 40 ); // 60px is the width, 40px is the height
}

// Display Most Popular Posts
function getPostViews($postID){
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
return "0 View";
}
return $count.' Views';
}
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);
}
}

2. Add the lines below to the sidebar.php file:

<div class="posts-most-popular widget">
<h4 class="widget-title">Most Popular</h4>
<ul>
	<?php 
	$theme_popular_posts = new WP_Query('meta_key=post_views_count&orderby=meta_value_num&order=DESC&posts_per_page=5');
	if ( $theme_popular_posts->have_posts() ) : while ($theme_popular_posts->have_posts()) : $theme_popular_posts->the_post(); 
	?>
		<li>
			<div class="image-widget"><a href="<?php esc_url(the_permalink()); ?>"><?php the_post_thumbnail(''); ?></a></div>
			<div class="title-widget"><a href="<?php esc_url(the_permalink()); ?>"><?php esc_html(the_title()); ?></a></div>
		</li>
	<?php endwhile; ?>
	<?php endif; ?>
	<?php wp_reset_postdata(); ?>
</ul>
</div>

3. Add the following bits of code into the single.php loop:

<?php setPostViews(get_the_ID()); ?>

4. Add the code below to the style.css file:

.widget-title {
font-size: 30px;
font-weight: bold;
padding-bottom: 5px;
}

.widget ul {
list-style-type: none;
text-align: left;
padding-left: 0;
margin-left: 0;
display: block;
}

.widget li {
margin-bottom: 40px;
height: 10px;
display: inline-block;
}

.widget li img {
display: inline-block;
margin-left: 0;
margin-right: 10px;
width: 60px;
height: 40px;
float: left;
}

.widget li a {
vertical-align: top;
}

Using a Plugin to Display Most Popular Posts

If you want to display your most popular posts using a plugin, WP Most Popular can help you. It is a simple and straightforward plugin that does the job.