In this post I am going to show How to Display Popular Posts by Views in WordPress
Step 1. Add these two function in theme function.php file
PHP
x
function da_get_views_post($post_id){
$key = 'post_views_count';
$count = get_post_meta($post_id,$key, true);
if($count == ''){
$count = 0;
delete_post_meta($post_id,$key);
add_post_meta($post_id,$key,$count);
}else{
$count++;
update_post_meta($post_id,$key, $count);
}
}
function da_get_post_views($post_id){
$key = 'post_views_count';
$count = get_post_meta($post_id,$key, true);
if($count == ''){
$count = 0;
delete_post_meta($post_id,$key);
add_post_meta($post_id,$key,$count);
return "0 View";
}
return $count. ' Views';
}
Step 2. Save view value in meta field
Call da_get_views_post() in single.php file
PHP
da_get_views_post(get_the_ID());
Step 3. Display Total view on single post
Call da_get_post_views() in single.php file
PHP
echo da_get_post_views(get_the_ID());
Step 4. Display Popular post
where you want to display popular posts add given code below
PHP
<?php
$args = [
'post_type'=> 'post',
'posts_per_per' => 3,
'meta_key' => 'post_views_count',
'orderby' => 'meta_value_num',
'order'=> 'desc'
];
$popular = new WP_Query($args);
while ($popular->have_posts()): $popular->the_post();
the_post_thumbnail();
the_title('<h2>','</h2>');
the_excerpt();
endwhile; wp_reset_postdata();
?>
Thank you!
I’m so glad it was helpful!