functions - How to Display Most View Post in the template file?

admin2025-01-07  3

I need to create most viewed post column in the template file, but based on post view count?

Function File

function wpb_get_post_views($postID){
$count_key = 'wpb_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';
}

Template File

<?php 
$popularpost = new WP_Query( array( 'posts_per_page' => 4, 'meta_key' => 'wpb_post_views_count', 
'orderby' => 'meta_value_num', 'order' => 'DESC'  ) );
 while ( $popularpost->have_posts() ) : $popularpost->the_post();
 the_title();
 endwhile;
?>

I need to create most viewed post column in the template file, but based on post view count?

Function File

function wpb_get_post_views($postID){
$count_key = 'wpb_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';
}

Template File

<?php 
$popularpost = new WP_Query( array( 'posts_per_page' => 4, 'meta_key' => 'wpb_post_views_count', 
'orderby' => 'meta_value_num', 'order' => 'DESC'  ) );
 while ( $popularpost->have_posts() ) : $popularpost->the_post();
 the_title();
 endwhile;
?>
Share Improve this question edited Nov 17, 2017 at 6:36 asked Nov 17, 2017 at 6:04 user131591user131591 3
  • Not sure what you are asking. Maybe you can add more information or some use cases. – Drupalizeme Commented Nov 17, 2017 at 6:24
  • brother i need to display most viewed post in the template file without any plugin? – user131591 Commented Nov 17, 2017 at 6:37
  • Where is wpb_post_views_count coming from? Note that tracking view counts via post meta is extremely unreliable, suffers from race conditions leading to undercounting, and is fundamentally incompatible with fullpage caching and CDNs – Tom J Nowell Commented Aug 5, 2022 at 15:10
Add a comment  | 

1 Answer 1

Reset to default 0

The function getPostViews() is retrieving the total number of views for each post while setPostViews() increases the post views counter each time post is viewed. You need to call setPostViews() somewhere in your single.php and then use below code to retrieve posts on basis of posts view count.

$args = Array(
  'post_type' => 'post',
  'posts_per_page' => '5',
  'meta_key' => 'post_views_count',
  'orderby' => 'meta_value_num',
  'order' => 'DESC'
);
$popular = new WP_Query( $args );

<?php while($popular->have_posts()) : $popular->the_post();  ?>

    <?php the_post_thumbnail(); ?> <?php the_title(); ?> <?php the_content(); ?>

<?php endwhile ?>
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736255290a270.html

最新回复(0)