Skip to content

Instantly share code, notes, and snippets.

@danphilibin
Created March 15, 2012 05:10
Show Gist options
  • Save danphilibin/2042048 to your computer and use it in GitHub Desktop.
Save danphilibin/2042048 to your computer and use it in GitHub Desktop.
WordPress post view counter
// update view count for a post
function update_post_views($postID=0) {
$view_count = get_post_meta($postID, '_view_count', true);
if(!$view_count) $view_count = 0;
update_post_meta($postID, '_view_count', $view_count+1);
}
// usage within loop:
<?php update_post_views($post->ID); ?>
// query:
$query = new WP_Query(array(
'post_type' => 'post',
'posts_per_page' => '4',
'meta_key' => '_view_count',
'orderby' => 'meta_value'
));
while($query->have_posts()) : $query->the_post();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment