WordPress - Track Post Views

<?php function hmk_get_post_views($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 hmk_set_post_views($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); } } // Remove issues with prefetching adding extra views remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0); // Place this function in single.php hmk_set_post_views(get_the_ID()); // Use this function anywhere you want to display the post views hmk_get_post_views(get_the_ID());

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.