WordPress’ WP_Query
has orderby=rand
parameter to make WP_Query
displays random posts1 but there’s no native parameter to randomly displays WP_Query posts output2 inside The Loop. I faced this need and found a workaround for that:
- Get a
WP_Query
object using parameters you want - Assuming you’re using
$posts
as the variable of yourWP_Query
object, the posts data that will be used for ‘The Loop’ can be accessed at$posts->posts
. - Store and convert
$posts->posts
into array so you can shuffle the order of the posts - Shuffle the “array”-ed posts
- Convert the shuffled posts into object
- Assign back the shuffled posts object to
$posts->posts
- Now you can start outputing the object using “the loop”
Here’s how it looks in form of code: