Skip to content

Instantly share code, notes, and snippets.

@vsmith72
Created November 17, 2016 00:29
Show Gist options
  • Save vsmith72/27d7b298802659f731080dff1ae7b43e to your computer and use it in GitHub Desktop.
Save vsmith72/27d7b298802659f731080dff1ae7b43e to your computer and use it in GitHub Desktop.
Popular Posts
// use this for getting popular posts without a plug in
// this is the code for the functions.php
// paste as is no spaces
function getPostViews($postID){
$count_key = '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';
}
function setPostViews($postID) {
$count_key = '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);
}
}
// this code goes in your single.php after the_content();
// it counts the views
<?php setPostViews(get_the_ID()); ?>
// this is the loop, put where you want to display the posts
// edit ccs and html to fit your theme
<h3>Popular Stuff:</h3>
<?php
$popularpost = new WP_Query( array( 'posts_per_page' => 4, 'meta_key' => 'post_views_count', 'orderby' => 'meta_value_num', 'order' => 'DESC' ) );
while ( $popularpost->have_posts() ) : $popularpost->the_post();?>
<li>
<a href="<?php the_permalink() ?>" title="<?php the_title();?>"><h1><?php the_title();?></h1></a>
</li>
<?php endwhile; ?>
<?php wp_reset_query(); ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment