Skip to content

Instantly share code, notes, and snippets.

@dasbairagya
Last active July 5, 2018 04:36
Show Gist options
  • Select an option

  • Save dasbairagya/24ed1115b15c383a53b0b4978a10531c to your computer and use it in GitHub Desktop.

Select an option

Save dasbairagya/24ed1115b15c383a53b0b4978a10531c to your computer and use it in GitHub Desktop.
How to fetch the popular post in wordpress according to views
<?php
/* for popular post*/
/* set the post view count*/
function wpb_set_post_views($postID) {
$count_key = 'wpb_post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
$count = 0;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
}else{
$count++;
update_post_meta($postID, $count_key, $count);
}
}
//To keep the count accurate, lets get rid of prefetching
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
/* get the post view count*/
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';
}
?>
<ul class="blog-list-sidebar">
<?php
//set your post type
$popularpost = new WP_Query( array( 'post_type'=>'blog', 'posts_per_page' => 5, 'meta_key' => 'wpb_post_views_count', 'orderby' => 'meta_value_num', 'order' => 'DESC' ) );
while ( $popularpost->have_posts() ) : $popularpost->the_post();
$url = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
?>
<li>
<div class="post-thumb"> <a href="<?php the_permalink();?>"><img src="<?php echo $url ;?>" alt="Blog"></a> </div>
<div class="post-info">
<h5 class="entry_title"><a href="<?php the_permalink();?>"><?php the_title();?></a></h5>
<div class="post-meta"> <span class="date"><i class="pe-7s-date"></i> 2014-08-05</span> <span class="comment-count"> <i class="pe-7s-comment-o"></i> 3 </span> </div>
</div>
</li>
<?php endwhile; ?>
</ul>
<?php
if ( have_posts() ) :
while ( have_posts() ) : the_post();
$url = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
wpb_set_post_views($post->ID);//this function has been define in functions.php
echo wpb_get_post_views($post->ID);?>) //this function shows the total no of views for the post.
?>
//some stufs
<?php endwhile;endif; ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment