-
-
Save secp8x32/b488e72fa110a1dda191f17ab0203b13 to your computer and use it in GitHub Desktop.
Display Popular Posts by Views in WordPress without a Plugin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function whpp_track_post_views($post_id) { | |
if (!is_single()) | |
return; | |
if (empty($post_id)) { | |
global $post; | |
$post_id = $post->ID; | |
} | |
whpp_set_post_views($post_id); | |
} | |
add_action('wp_head', 'whpp_track_post_views'); | |
function whpp_set_post_views($post_id) { | |
$count_key = 'whpp_track_post_views'; | |
$count = get_post_meta($post_id, $count_key, TRUE); | |
if ($count == '') { | |
$count = 0; | |
delete_post_meta($post_id, $count_key); | |
add_post_meta($post_id, $count_key, '0'); | |
} else { | |
$count++; | |
update_post_meta($post_id, $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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment