Skip to content

Instantly share code, notes, and snippets.

@UmeshSingla
Last active December 17, 2015 20:29
Show Gist options
  • Save UmeshSingla/5668126 to your computer and use it in GitHub Desktop.
Save UmeshSingla/5668126 to your computer and use it in GitHub Desktop.
Wordpress Popular Post(No. of Post Views)
<?php
/* Add this code to function.php file */
/* Post View Increment */
function rtp_popular_post(){
global $post;
$count_key = '_rtp_post_view_count';
if(is_single()){
$view_count = get_post_meta($post->ID, $count_key, true);
if($view_count==''){
$view_count = 0;
//Delete all custom fields with the specified key from the specified post.
delete_post_meta($post->ID, $count_key);
//Add a custom (meta) field (Name/value)to the specified post.
add_post_meta($post->ID, $count_key, '0');
}
else
$view_count++;
update_post_meta($post->ID, $count_key, $view_count);
}
}
add_action('wp','rtp_popular_post'); ?>
<?php
/* Add this code to display post acc. to view count */
$args = array(
'numberposts' => 4, //get all posts, or set a number here
'offset' => 0,
'orderby' => 'meta_value_num', //this will look at the meta_key you set below
'order' => 'DESC', //You can order by ASC (ascending) or DESC (descending)
'meta_key' => '_rtp_post_view_count', //Set the meta key here, NOT the meta value. WordPress will get the value on its own
'post_type' => 'post', //got a custom post type? Put it here
'post_status' => 'publish' );
$results = get_posts( $args );
?>
<div id="popular-posts-2" class="widget sidebar-widget widget_recent_entries">
<h3 class="widgettitle">Popular Posts</h3>
<ul>
<?php
foreach($results as $post_new){
echo '<li><a title="'.$post_new->post_title .'" href="'. get_permalink($post_new->ID).'">'.$post_new->post_title.'</a></li>';
}
?>
</ul>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment