Created
March 25, 2019 17:05
-
-
Save raazon/0db78b8dd9832b413d5834eb61080ec1 to your computer and use it in GitHub Desktop.
Display Popular Posts by Views in WordPress without a Plugin
This file contains 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 | |
/** | |
* 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'); |
This file contains 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 | |
// QUERY ARGUMENTS | |
$args = array( | |
'post_type' => 'apps', | |
'posts_per_page' => -1, | |
); | |
$args['meta_key'] = 'post_views_count'; | |
$args['orderby'] = 'meta_value_num'; | |
$args['order'] = 'DESC'; | |
// The Query | |
$the_query = new WP_Query( $args ); | |
// The Loop | |
if ( $the_query->have_posts() ) { | |
echo '<ul>'; | |
while ( $the_query->have_posts() ) { | |
$the_query->the_post(); | |
echo '<li>' . get_the_title() . '</li>'; | |
} | |
echo '</ul>'; | |
/* Restore original Post Data */ | |
wp_reset_postdata(); | |
} else { | |
// no posts found | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment