Display query post based on two orderby value in wordpress

I have been trying to display popular posts (based on view counts) and fetching them randomly using array in orderby but it doesn't seem to be working. The reason I want them to display randomly is because I don't want the same post to be displayed repeatedly to both new repeated visitors as the views count increases naturally.

Here is the code I tried:

$popularpost = new WP_Query(
    array(
        'category'          = 'comedy',
        'posts_per_page'    =  4,
        'meta_key'          = 'post_views_count',
        'orderby'           = array ('meta_value_num', 'rand'),   //this is the one I want both rand  meta_value_num to retrieve
        'order'             = 'DESC'
    ) 
);

while ( $popularpost-have_posts() ) : $popularpost-the_post();
    the_permalink();
    the_title();
    if ( has_post_thumbnail() ):
        the_permalink(' ');the_title();
        the_post_thumbnail();
    endif;
    the_excerpt(); // echo the excerpt
endwhile;

Everything is working except that it doesn't fetch randomly. The same post are always shown.

Topic menu-order meta-query popular-posts Wordpress

Category Web


I think it might be very easy for you to get the top 25 based on view count and then get a random selection of 4 from that list.

Below is an easy to test query but you would want to replace with just your post_views_count query and remove any rand orderby.

// get top 25
$posts = get_posts( array (
    'post_type'      => array ( 'post' ),
    'posts_per_page' => 25,
    'fields'         => 'ids',
) );

// randomize the top 25
shuffle( $posts );

// pull to first 4 items
$posts = array_slice( $posts, 0, 4 );

// show the results
echo "<pre>";
foreach ( $posts as $post_id ) {
    echo get_the_title( $post_id ) . PHP_EOL;
}

Using your query:

// query the top posts
$popularpost = new WP_Query(
    array(
        'category'          => 'comedy',
        'posts_per_page'    =>  25, // top 25
        'meta_key'          => 'post_views_count',
        'orderby'           => array ('meta_value_num'),
        'order'             => 'DESC'
    )
);

// randomize the items
shuffle($popularpost->posts);

// limit the the number of posts
$popularpost->posts = array_slice( $popularpost->posts, 4); // random 4 posts

// output
while ( $popularpost->have_posts() ) : $popularpost->the_post();
    the_permalink();
    the_title();
    if ( has_post_thumbnail() ):
        the_permalink(' ');the_title();
        the_post_thumbnail();
    endif;
    the_excerpt(); // echo the excerpt
endwhile;

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.