How to use order RAND() on WordPress?

Attention: It’s order, not orderby.

According to wordpress docs, there are only two options to order, which are ASC or DESC.

The problem is:

I would like to randomize the posts I’ve selected, not randomize WHICH posts I select.

Here’s my code for better explanation:

<?php
return array(
  "post_type" => "listings",
  "post_status" => "publish",
  'meta_query'=>array(
                        array('key'=>'featured_until','value'=>$current_date, 'compare'=>'>'),
                     ),
  'meta_key'=>'featured_until',
  "orderby" => array(
            'featured_until' => 'RAND', /* How can I make this work? */
            'date' => 'DESC'
  ),
  "suppress_filters" => true,
  "facetwp" => true,
  "posts_per_page" => 16
);

It’s a listings website. The code above selects 16 posts to show on the first page.

First, it tries to find 16 featured listings. If there aren’t that many featured listings, it completes with regular listings ordered by date.

The question is: How can I order the featured listings by RANDOM, instead of ASC or DESC?

3 Answers
3

You are right that you can’t have WordPress order the retrieved posts randomly. So you’ll have to do that yourself after you have retrieved the array of post objects. Let’s call that $my_posts.

Because you don’t know how many of the posts in that array are featured, you will have to loop through them to split the array. I don’t know how exactly you have defined ‘featured’, but it would look something like this:

$featured_posts = array ();
$nonfeatured_posts = array ();
foreach ($my_posts as $my_post) {
  if (test if featured)
    $featured_posts[] = $my_post
  else
    $nonfeatured_posts[] = $my_post;
// now, let's randomize
shuffle ($featured_posts);
// join the array again
$my_posts = array_merge ($featured_posts,$nonfeatured_posts);
// now you have your array with featured posts randomized

Beware, I couldn’t test this code, but I trust you get the point.

Leave a Comment