Home > database >  Sorting by post views count doesnt work. Plugin: "Post Views Counter" - Wordpress
Sorting by post views count doesnt work. Plugin: "Post Views Counter" - Wordpress

Time:09-27

Im making news blog and I need to display daily posts.

How doest daily posts work in my blog? : Im picking all posts for this day and sorting them by views count.

There is the problem: I can't sort by views count with Post Views Counter plugin. It doesnt returning any posts on WP_Query.

My tryings:

function DisplayDailyNews(){
    $yesterday = date('d.m.Y',strtotime("yesterday"));
    $yesterdayarray = date_parse($yesterday);

    $dailyGridPostQuery = new WP_Query(array(
        "post_type"             => "post",
        "post_status "          => "publish",
        "posts_per_page"        => 3,
        "day"                   => $yesterdayarray["day"],
        "meta_key"              => "post_views_count",
        "orderby"               => "meta_value_num",
        "order"                 => "DESC"
    ));

    if ($dailyGridPostQuery->have_posts()){
        while ($dailyGridPostQuery->have_posts()){
            $dailyGridPostQuery->the_post(); 
            //Displaying post item here...
        } 
    }
}

I tried googling a solution but none of them worked for me.


FAQ1: Yes, I have posts for this day.

CodePudding user response:

This plugin dont use custom field post_views_count for save post_count Its create additional table

$wpdb->prefix . "post_views

To order posts by post_views use

"orderby" => "post_views",

try this code

$dailyGridPostQuery = new WP_Query(array(
    "post_type"             => "post",
    "post_status "          => "publish",
    "posts_per_page"        => 3,
    "year"                  => $yesterdayarray["year"],
    "monthnum"              => $yesterdayarray["month"],
    "day"                   => $yesterdayarray["day"],
    "orderby"               => "post_views",
    "order"                 => "DESC"
));

P.S. post_views need to be > 0

  • Related