Skip to content

Instantly share code, notes, and snippets.

@deeman
Last active September 29, 2019 11:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deeman/2deaa9a4229f134e0bbb088a265e26ac to your computer and use it in GitHub Desktop.
Save deeman/2deaa9a4229f134e0bbb088a265e26ac to your computer and use it in GitHub Desktop.
WordPress: Show most popular posts without a plugin
//Add this anywhere in your template where you wish to display the posts.
<?php
$popular_posts_args = array(
'posts_per_page' => 3,
'meta_key' => 'my_post_viewed',
'orderby' => 'meta_value_num',
'order'=> 'DESC'
);
$popular_posts_loop = new WP_Query( $popular_posts_args );
while( $popular_posts_loop->have_posts() ):
$popular_posts_loop->the_post();
// Loop continues
endwhile;
wp_reset_query();
?>
// Add this code to your functions.php file.
function count_post_visits() {
if( is_single() ) {
global $post;
$views = get_post_meta( $post->ID, 'my_post_viewed', true );
if( $views == '' ) {
update_post_meta( $post->ID, 'my_post_viewed', '1' );
} else {
$views_no = intval( $views );
update_post_meta( $post->ID, 'my_post_viewed', ++$views_no );
}
}
}
add_action( 'wp_head', 'count_post_visits' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment