Home Ask Login Register

Developers Planet

Your answer is one click away!

SarpSTA February 2016

How can I make so that the order of this loop's output is random?

In my Wordpress site, my taxonomy-product-category.php template has the following loop for loading posts into the page:

<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>

However, I want the posts to be randomly ordered rather than following a specific order like date added.

How can I modify this loop to do it?


WheatBeak February 2016


<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>


$args = array(
    'cat' => YOUR CATEGORY ID,
    'post_type' => YOUR CUSTOM POST TYPE,
    'orderby' => 'rand'

$query = new WP_Query($args);

<?php if ($query->have_posts()) : ?>
<?php while ($query->have_posts()) : $query->the_post(); ?>

Pieter Goosen February 2016

You can use pre_get_posts to set random ordering to your taxonomy pages. Just note, random ordering duplicates posts between paged pages as each page is a new query and not an extension to one. This is unfortunately how random ordering works.

You can try the following

add_action( 'pre_get_posts', function ( $q )
    if (    !is_admin() // Only targets the front end
         && $q->is_main_query() // Only targets the main query
         && $q->is_tax( 'product-category' ) // Only targets the product-category tax pages
    ) {
        $q->set( 'orderby', 'rand' );

Post Status

Asked in February 2016
Viewed 1,945 times
Voted 4
Answered 2 times


Leave an answer

Quote of the day: live life