Benjamin Park
Benjamin Park

Reputation: 71

WP_Query ordering by "rand" and "name"?

I am using Wordpress and for the posts on my homepage, I want them to get ordered both randomly and by name. What I mean is, I want to show different posts on my home page each time, yet ordered by their names. I changed the WP_Query args from my theme files as below, but it didn't work. I'm getting unrelated results for a reason I can't understand.

#setup wp_query
$args = array(
    'posts_per_page' => $postsperpage, 
    'orderby' => array( 'rand', 'title' ),
    'order'   => 'DESC',
);

Is there any way to make that possible?

p.s. I am honestly sick of those who downvote the questions irrelevantly. I wouldn't have asked the question should i had found a solution on the internet. If you have a logical reason please either warn me or edit my post instead of blindly downvoting it.

Upvotes: 5

Views: 15363

Answers (1)

Gerald Schneider
Gerald Schneider

Reputation: 17797

As documented:

orderby (string | array) - Sort retrieved posts by parameter. Defaults to 'date (post_date)'. One or more options can be passed.

So:

$args = array(
    'orderby' => array( 'rand', 'name' ),
    'order'   => 'DESC',
);

But I don't think this will get you the result you desire. You will most probably have to only use rand with posts_per_page setting to get your desired number of posts. Fetch all posts and sort these by name afterwards.

Example:

$args = array(
    'orderby' => 'rand',
);
// get X random posts (10 by default)
$result = new WP_query( $args );

// sort these posts by post_title
usort( $result->posts, function($a, $b) {
    if ( $a->post_title == $b->post_title )
        return 0;
    return ($a->post_title < $b->post_title) ? -1 : 1;
} );

// Start the loop with posts from the result.
while ( $result->have_posts() ) : $result->the_post();
    // do your stuff in the loop
}

Upvotes: 8

Related Questions