wp query - Get random terms

admin2025-01-08  3

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
) );
Share Improve this question asked Jun 14, 2017 at 14:17 RiesvGeffenRiesvGeffen 1351 silver badge5 bronze badges 1
  • random anything is very bad for caching. if you have no preference about which terms to display, the latest N is as random to the user of the site as any other set of terms ;) – Mark Kaplun Commented Jun 14, 2017 at 14:50
Add a comment  | 

2 Answers 2

Reset to default 13

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
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736268641a1290.html

最新回复(0)