Is it possible to get random terms? To get random posts you could use WP_Query
and set 'orderby' => 'rand'
.
But is there any way to do that with terms?
I've tried this:
$terms = get_terms( array(
'taxonomy' => 'webshops',
'hide_empty' => false,
'orderby' => 'rand',
'number' => 6
) );
Is it possible to get random terms? To get random posts you could use WP_Query
and set 'orderby' => 'rand'
.
But is there any way to do that with terms?
I've tried this:
$terms = get_terms( array(
'taxonomy' => 'webshops',
'hide_empty' => false,
'orderby' => 'rand',
'number' => 6
) );
Unlike a normal WP_Query()
, get_terms()
or WP_Term_Query()
does not have random ordering. You would either need to do it in SQL yourself or grab all the terms and shuffle them, pulling out 6 to make your random term array:
// Get all terms
$terms = get_terms( array(
'taxonomy' => 'webshops',
'hide_empty' => false,
) );
// Randomize Term Array
shuffle( $terms );
// Grab Indices 0 - 5, 6 in total
$random_terms = array_slice( $terms, 0, 6 );
While the other answer provides a viable option for sites with a small amount of terms, in cases where the amount isn't all that low, fetching all the terms and doing the shuffling on the PHP side will lead to wasted resources and slowdown.
A much better approach is to actually force the SQL query from WP_Term_Query
class to do a real random ORDER BY
at the SQL level.
That piece of code will work much better than the PHP side randomisation.
function make_rand($orderby, $q) {
if ($q['orderby'] === 'rand') {
return 'RAND()';
}
return $orderby;
}
add_filter('get_terms_orderby', 'make_rand', 10, 2);
$terms = get_terms([
'taxonomy' => 'webshops',
'hide_empty' => false,
'orderby' => 'rand',
'number' => 6
]);
remove_filter('get_terms_orderby', 'make_rand', 10, 2);
// $terms are in random order here