I'm using a transient to store a query that gets 60 posts and makes a mosaic of background images, because it improves performance greatly.

The query has 'orderby' =>'rand' set, but obviously when it's retrieved from the transient it displays the same each time.

My question is, can I make the loop display the results of the query in a random order? This would then equal my original state with much better performance.

Thank you.

  • There really is no sane method of using transients for random queries. Transients and caches are really meant to be use with data that stays static across a set amount of time, and not for random queries that changes on each page load. Creating and flushing transients are expensive operations, so you would not want to create and flush them on every page load or every x amount of minutes Nov 9, 2015 at 7:54
  • To clarify, I do plan on using the transient to store my query results for a (long) set amount of time, but I was wondering if I can display them randomly each time, despite them being the same. But I think you answered me either way.
    – VesterDe
    Nov 9, 2015 at 8:05
  • 1
    Please add the relevant code snippets to your question @VesterDe
    – birgire
    Nov 9, 2015 at 8:16

1 Answer 1


As I understood, you want the same results but randomize their order. So, you need to shuffle that results. That is quite simple using shuflle() PHP function. But that function needs arrays, not objects.

You could convert the object from WP_Query to an array or, I think better, use get_posts() instead of WP_Query.

$args = array(
    // Arguments to get posts

$posts = get_transient ( "your-transiente-name" );

if( $posts === false ) {
    $posts =  get_posts( $args );
    set_transient( "your-transiente-name", $posts, "the-expiration-time" );

// Shuffle the $post array
$posts = shuffle( $posts );

foreach( $posts as $post ) {
    setup_postdata( $post );
    // Standard loop stuff

  • 1
    You can still use WP_Query. No need to convert to an array Nov 9, 2015 at 8:26
  • Please, show me how; using shuffle() with objects is out of my knowledge. ;)
    – cybmeta
    Nov 9, 2015 at 8:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.