There is no default way to sort terms randomly. There are ways to do this using php.
First, you’ll need to remove the number
argument from get_terms
. As your code currently stands, you are getting 5 terms and shuffling them around.
For this to work, you’ll need to retrieve all the terms from your taxonomy, shuffle that returned array randomly with the php function shuffle()
, pass that through a foreach
loop, create a new array and then use array_slice
to to get the first 5 entries
Here is just a rough idea
$all_artists = get_terms( 'category' );
shuffle( $all_artists );
$term_names = [];
foreach ( $all_artists as $cat )
$term_names[] = $cat->name;
$output = array_slice( $term_names, 0, 5 );
foreach ( $output as $key=>$value )
echo '<p>' . $value . '</p>';
EDIT
Here is another way to achieve the same. This involves creating a custom function that will sort the array randomly, and keeping the key/value pairs in place. This function comes from this answer on SO by @karim79
You can then use array_slice()
to get the first % key/value pairs
function shuffle_assoc( $list )
{
if ( !is_array( $list ) )
return $list;
$keys = array_keys( $list );
shuffle( $keys );
$random = [];
foreach ( $keys as $key )
{
$random[$key] = $list[$key];
}
return $random;
}
$terms = get_terms( 'category' );
$output = array_slice( shuffle_assoc( $q ), 0, 5 );
?><pre><?php var_dump($output)); ?></pre><?php