Last active
April 14, 2019 09:13
-
-
Save micjamking/d9955d4d99841e10e2fa2614eb3ec728 to your computer and use it in GitHub Desktop.
[WordPress] Display Popular Posts by Page 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 | |
/** | |
* Sets the post view count | |
* @params ($postID) Current post ID | |
*/ | |
function namespace_set_post_views($postID) { | |
$count_key = 'namespace_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); | |
} | |
} | |
/** | |
* Track post views on page load | |
* @params ($postID) Current post ID | |
*/ | |
function namespace_track_post_views ($post_id) { | |
if ( !is_single() ) return; | |
if ( empty ( $post_id) ) { | |
global $post; | |
$post_id = $post->ID; | |
} | |
namespace_set_post_views($post_id); | |
} | |
/** | |
* To keep the count accurate, remove prefetching of posts | |
*/ | |
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0); | |
/** | |
* Add post view tracker to page head | |
*/ | |
add_action( 'wp_head', 'namespace_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 | |
/** | |
* Popular Posts WP Query | |
*/ | |
$args = array( | |
'posts_per_page' => 4, | |
'meta_key' => 'namespace_post_views_count', | |
'orderby' => 'meta_value_num', | |
'order' => 'DESC' | |
); | |
$popularpost = new WP_Query( $args ); | |
?> | |
<?php if ( $popularpost->have_posts() ) : ?> | |
<ul> | |
<?php while ( $popularpost->have_posts() ) : $popularpost->the_post(); ?> | |
<li> | |
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a> | |
</li> | |
<?php endwhile; wp_reset_postdata(); ?> | |
</ul> | |
<?php endif; ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment