Skip to content

Instantly share code, notes, and snippets.

@pixelbart
Last active July 28, 2021 15:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pixelbart/ae7f108a972600d2843fc157cd0f4036 to your computer and use it in GitHub Desktop.
Save pixelbart/ae7f108a972600d2843fc157cd0f4036 to your computer and use it in GitHub Desktop.
WooCommerce REST API: Random sorting for products and other post types.

Usage example

Endpoint: {your_website}/wp-json/wc/v3/products?orderby=rand

<?php // functions.php
/**
* rest_{post_type}_collection_params
*
* @param array $params
* @return array
*/
add_filter( 'rest_product_collection_params', function ( $params ) {
$params['orderby']['enum'][] = 'rand';
return $params;
});
@sarimoon98
Copy link

Thank you. This helps me a lot.

However, I have a question.
How to change the default orderby to rand ?

@pixelbart
Copy link
Author

@sarimoon98

add_action('pre_get_posts' function($query) {
    if ($query->is_main_query() && ! is_admin()) {
        $query->set("orderby", "rand");
    }
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment