Skip to content

Instantly share code, notes, and snippets.

@bueltge
Created July 21, 2011 15:25
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bueltge/1097431 to your computer and use it in GitHub Desktop.
Save bueltge/1097431 to your computer and use it in GitHub Desktop.
count the number of hits on a specific page in WordPress
function count_page_hits() {
if ( is_single() ) {
global $post;
$count = get_post_meta( $post -> ID, 'count_page_hits', true );
$newcount = $count + 1;
update_post_meta( $post -> ID, 'count_page_hits', $newcount );
}
}
add_action( 'wp_head', 'count_page_hits' );
***
MORE USABLE
// function to display number of posts.
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 to 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);
}
}
on single.php/page.php --> setPostViews( get_the_ID() );
for echo --> echo getPostViews(get_the_ID());
Simple echo on backend -->
add_filter('manage_posts_columns', 'posts_column_views');
add_action('manage_posts_custom_column', 'posts_custom_column_views',5,2);
function posts_column_views($defaults){
$defaults['post_views'] = __('Views');
return $defaults;
}
function posts_custom_column_views($column_name, $id){
if($column_name === 'post_views'){
echo getPostViews(get_the_ID());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment