Skip to content

Instantly share code, notes, and snippets.

@ElmahdiMahmoud
Created October 31, 2013 12:10
Show Gist options
  • Select an option

  • Save ElmahdiMahmoud/7248642 to your computer and use it in GitHub Desktop.

Select an option

Save ElmahdiMahmoud/7248642 to your computer and use it in GitHub Desktop.
wp: Get post views
<?php
/* functions.php */
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);
}
}
?>
<!-- single.php -->
<?php setPostViews(get_the_ID()); ?>
<!-- place it where you want to display views! -->
<?php echo getPostViews(get_the_ID()); ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment