Skip to content

Instantly share code, notes, and snippets.

@beovulf
Last active February 5, 2016 07:59
Show Gist options
  • Save beovulf/ba9e5d4890cd872aa4e1 to your computer and use it in GitHub Desktop.
Save beovulf/ba9e5d4890cd872aa4e1 to your computer and use it in GitHub Desktop.
Post counter
/////////////// IN FUNCTION.PHP ///////////////
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);
/////////////// INSERT CODE BELOW TO TEMPLATE TO INITIALIZE COUNTING ///////////////
wpb_set_post_views(get_the_ID());
/////////////// WIDGET ///////////////
<?php
$popularpost = new WP_Query( array( 'post_type' => array('page','post'), 'posts_per_page' => 5, 'meta_key' => 'wpb_post_views_count', 'orderby' => 'meta_value_num', 'order' => 'DESC' ) );
while ( $popularpost->have_posts() ) : $popularpost->the_post();?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile;?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment