I am working in WordPress and I am trying to order the product results randomly. Like every time a customer refresh the page then the products should be randomly shown. Currently no matter how many times I refresh the page.
Each time products are showing in the same order. The first product will be at first and last will be at last.
I am writing this query
add_action( 'pre_get_posts', 'rand_products');
function rand_products( $query) {
//if ( ! is_admin() && $query->is_main_query() ) {
$query->query['orderby'] = 'rand';
$query->query['order'] = 'rand';
$query->set( 'orderby', 'rand');
$query->set( 'order', 'rand' );
/}
}
If I see the query dump(attached in the screenshot) then I can see that query parameters have been changed but Still it is not working. Can anyone Please help.
2
Answers
The troubleshoot might be coming from the fact that you’re using an undefined value for the
order
parameter.As per the
WP_Query
order & order by parameters:order (string | array)
– Designates the ascending or descending order of the ‘orderby‘ parameter. Defaults toDESC
. An array can be used for multiple order/orderby sets.ASC
– ascending order from lowest to highest values (1, 2, 3; a, b, c).DESC
– descending order from highest to lowest values (3, 2, 1; c, b, a).orderby (string | array)
– Sort retrieved posts by parameter. Defaults todate (post_date)
. One or more options can be passed.rand
– Random order.As you can see only
orderby
can take arand
value.order
should be set to eitherDESC
descending order orASC
ascending order.Your code is worked. I had check in my local.
I have one suggestion for this, any used theme or installed plugine may be conflict for this code.
Add Priority