Diwakar Academy

  • Home
  • WordPress
  • About Us
  • Contact Us
You are here: Home / WordPress / How to Display Popular Posts by Views in WordPress

November 14, 2022

How to Display Popular Posts by Views in WordPress

Spread the love

In this post I am going to show How to Display Popular Posts by Views in WordPress

Table of Contents

Toggle
  • Step 1. Add these two function in theme function.php file
  • Step 2. Save view value in meta field
  • Step 3. Display Total view on single post
  • Step 4. Display Popular post

Step 1. Add these two function in theme function.php file

function da_get_views_post($post_id){
    $key = 'post_views_count';

    $count = get_post_meta($post_id,$key, true);

    if($count == ''){
        $count = 0;

        delete_post_meta($post_id,$key);

        add_post_meta($post_id,$key,$count);

    }else{
        $count++;
        update_post_meta($post_id,$key, $count);
    }
}

function da_get_post_views($post_id){
    $key = 'post_views_count';
    $count = get_post_meta($post_id,$key, true);

    if($count == ''){
        $count = 0;

        delete_post_meta($post_id,$key);

        add_post_meta($post_id,$key,$count);

        return "0 View";

    }

    return $count. ' Views';
}

Step 2. Save view value in meta field

Call da_get_views_post() in single.php file

da_get_views_post(get_the_ID());

Step 3. Display Total view on single post

Call da_get_post_views() in single.php file

echo da_get_post_views(get_the_ID());

Step 4. Display Popular post

where you want to display popular posts add given code below

<?php

        $args = [
                'post_type'=> 'post',
            'posts_per_per' => 3,
            'meta_key' => 'post_views_count',
            'orderby' => 'meta_value_num',
            'order'=> 'desc'

        ];

        $popular = new WP_Query($args);

        while ($popular->have_posts()): $popular->the_post();
            the_post_thumbnail();
            the_title('<h2>','</h2>');
            the_excerpt();
        endwhile; wp_reset_postdata();

        ?>

Article by Diwakar Academy / WordPress 2 Comments

Comments

  1. whoiscall says

    September 8, 2023 at 3:04 pm

    Thank you!

    Reply
    • Diwakar Academy says

      September 9, 2023 at 11:35 am

      I’m so glad it was helpful!

      Reply

Leave a Reply Cancel reply

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

  • Home
  • WordPress
  • About Us
  • Contact Us

Copyright © 2025 · All Rights Reserved · Terms and Conditions · Privacy Policy