Randomize Output for archive query

Really loving the query block for archives! Recently there was some discussion about using the query block for similar posts for single docs, and one of the lines of code was
$query_args[‘orderby’] = ‘rand’;

So I wondered if it was possible to take an archive query, where the arguments were specified in the block, but still randomize the resulting output?

Hi @willwenzel,

Yes, that code should still work and randomize the posts even if you have Parameters in your Query Loop.

1 Like

Thanks Fernando, and I tried it the way it’s written, but it’s specific to single posts, and so doesn’t display the archive page when I used it.

Can you share the current code you have?

Are you referring to the default WordPress Archive page? How are you adding the Query Loop to the Archive page?

Here’s the code I’m using, provided by you to a different question:
//try adding related blocks to category queries with few posts
add_filter( ‘generateblocks_query_loop_args’, function( $query_args, $attributes ) {
if ( ! empty( $attributes[‘className’] ) && strpos( $attributes[‘className’], ‘random’ ) !== false ) {

        $cat_values = get_category( get_query_var( 'cat' ) );
    

   

    $cat_slug = implode( ', ', $cat_values );
    $query_args['tax_query'] = array(
        array(
            'taxonomy' => 'category',
            'field' => 'slug',
            'terms' => $cat_slug,
        ),
    );

$query_args['orderby'] = 'rand';

}

return $query_args;

}, 10, 2 );
//end related blocks

The short answer to my archive pages is they’re just a page with a query block on them that pulls posts of a specific category, or multiple categories.
The long answer is I’m over-riding wordpress’ automatically generated archive pages with these, by following this tutorial: How To Replace A WordPress Category Archive With A Page

Well, I worked it out. I don’t need any coding in function, I just need to open my eyes and see that if I add a parameter to the block, that I can choose randomize!

Wow, just like me to try to make it harder :slight_smile:

Glad you resolved it @willwenzel!