skip to Main Content

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.

enter image description here

2

Answers


  1. 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:

    Parameters Values
    order (string | array) – Designates the ascending or descending order of the ‘orderby‘ parameter. Defaults to DESC. 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 to date (post_date). One or more options can be passed. rand – Random order.

    As you can see only orderby can take a rand value. order should be set to either DESC descending order or ASC ascending order.

    Login or Signup to reply.
  2. 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

    add_action( 'pre_get_posts','pre_get_posts', 999 );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search