Endpoint: {your_website}/wp-json/wc/v3/products?orderby=rand
Last active
July 28, 2021 15:19
-
-
Save pixelbart/ae7f108a972600d2843fc157cd0f4036 to your computer and use it in GitHub Desktop.
WooCommerce REST API: Random sorting for products and other post types.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
}); |
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
Thank you. This helps me a lot.
However, I have a question.
How to change the default orderby to rand ?