Skip to content

Instantly share code, notes, and snippets.

@raazon
Created March 25, 2019 17:05
Show Gist options
  • Save raazon/0db78b8dd9832b413d5834eb61080ec1 to your computer and use it in GitHub Desktop.
Save raazon/0db78b8dd9832b413d5834eb61080ec1 to your computer and use it in GitHub Desktop.
Display Popular Posts by Views in WordPress without a Plugin
<?php
/**
* POPULAR POSTS DATA SETUP
* It will set 'post_views_count' meta data to count popular posts
*/
function ic_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);
}
}
//To keep the count accurate, lets get rid of prefetching
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
function ic_track_post_views ($post_id) {
if ( ! is_singular('apps') ) return;
if ( empty ( $post_id) ) {
global $post;
$post_id = $post->ID;
}
ic_set_post_views($post_id);
}
add_action( 'wp_head', 'ic_track_post_views');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment