Want to display popular posts on your WordPress Website? There are many plugins available that can be installed to display popular posts. But adding an extra plugin for everything may decrease your website plugin. Instead of the plugin, here in this article, we will learn how to display popular posts on the WordPress website using functions.php of our theme.
Page Views are the best metrics that can help us identify the popularity of a post. So, all we need to do is whenever a user visits a post we will store the page views in the database. Then we will retrieve the data from the database and display it on our post page. Let us get started.
Steps to display popular post in WordPress
- 1. Create a function to count & store page views
- 2. Create a function to fetch page views
- 3. Display popular post in the sidebar
1. Create a function to count & store page views
In your theme’s functions.php add the below code to set page views for the post.
function tp_set_page_views() {
if( is_single() ) {
$views = get_post_meta( get_the_ID(), 'post_views_count', true );
if( $views == '' ) {
update_post_meta( get_the_ID(), 'post_views_count', '1' );
} else {
$views_no = intval( $views );
update_post_meta( get_the_ID(), 'post_views_count', ++$views_no );
}
}
}
add_action( 'wp_head', 'tp_set_page_views' );
2. Create a function to fetch page views
Now we will create a function tp_get_post_views to fetch the post views. Copy and add the below code in your functions.php.
function tp_get_post_views(){
$count = get_post_meta( get_the_ID(), 'post_views_count', true );
return $count==''?0:$count;
}
3. Display popular post in the sidebar
Copy and paste the below code in the sidebar.php of your theme to display the list of posts sorted by popularity. You can change the number of posts to be displayed by updating the value of posts_per_page in the code below.
<?php
$popular_posts_args = array(
'posts_per_page' => 3,
'meta_key' => 'post_views_count',
'orderby' => 'meta_value_num',
'order'=> 'DESC'
);
$popular_posts_loop = new WP_Query( $popular_posts_args );
while( $popular_posts_loop->have_posts() ):
$popular_posts_loop->the_post();
/* Loop continues */
endwhile;
wp_reset_query();
?>
Displaying post views in the post
Earlier in step 2, we created a function to fetch page views. The same function we can use inside our single post page to display the page views. Refer code below to display the page view in your post:
<?php
if(have_posts()){
while ( have_posts() ) :
the_post();
?>
<h1><?php echo the_title();?></h1>
<div>
<p>Views: <?php echo tp_get_post_views();?></p>
</div>
<?php
endwhile;
}
?>
Conclusion
I hope this article will help you display popular posts and pageviews on your WordPress website. Please share this article with your friends and provide your valuable feedback in the comment section below. Sharing is caring 😎.
No Responses