Sadly get_categories()
and get_terms()
won't likely ever support 'orderby' => 'rand'
which really leaves you with two options - get every category and select 5 randomly, or construct your own WP_Query
to query categories with 'orderby' => 'rand'
. The former is easier to implement, and will likely have better performance (unless you have an very large number of categories, perhaps).
So for your purposes, the following would suffice:
$categories = get_categories();
shuffle( $categories );
$categories = array_slice( $categories, 0, 5 );
After which $categories
would contain 5 randomly selected categories.
Technically, the rand_keys()
approach is slightly faster. But in practice the difference is negligible (we're talking nanoseconds), unless you're working with hundreds of thousands of categories.
It's worth noting that if your WordPress installation doesn't contain at least 5 categories the above code will throw an error (as would the snippet in your question), since you cannot take the first 5 elements of an array that's only say 3 elements long.
You could improve upon it by throwing it into a function to make it reusable and more flexible, and adding a couple checks to help avoid potential errors:
function get_random_categories( $number, $args = null ) {
$categories = get_categories( $args ); // Get all the categories, optionally with additional arguments
// If there aren't enough categories, use as many as possible to avoid an error
if( $number > count( $categories ) )
$number = count( $categories );
// If no categories are available or none were requested, return an empty array
if( $number === 0 )
return array();
shuffle( $categories ); // Mix up the category array randomly
// Return the first $number categories from the shuffled list
return array_slice( $categories, 0, $number );
}
With that function loaded, you could simply call $categories = get_random_categories( 5 );
to obtain an array containing 5 random categories - and if the installation has fewer than five categories in total, it would simply return as many as are available, in random order.
Obtaining random posts is much easier, as you can simply use the 'orderby' => 'rand'
argument, as you mentioned - when omitting taxonomy and category arguments, a query will return posts from all categories by default.