Heres a little trick on how to show a list of the most popular WordPress post by post read count – without using a plugin.

Instructions
Add this code to your functions.php file.

<?php
   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' );
?>

Then 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();
   endwhile;
   wp_reset_query();
?>

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

This could be the beginning of something great 🙌

"*" indicates required fields

Name*
Hidden
Hidden

By submitting this form: You agree to the processing of the submitted data in accordance with WP Dynamics Privacy Policy.

Contact Information
You can also write us an email or contact us by telephone.
Telephone +45 71 74 71 21

Support For support inquiries, please refer to our support section.

Recent Articles

Faust.js – A Headless Framework for WordPress

Faust.js is a Headless WordPress Framework that provides a set of tools for building front-end applications based on WordPress ...

How to Load (Enqueue) and Handle Assets and Dependencies in WordPress

In WordPress, instead of adding assets such as styles and JavaScript to the header, you can and should use ...

An Introduction to Google Tag Manager Server-side Tagging

WordPress has come a long way since its launch in 2003 - from a blogging tool to a full-fledge ...