{"id":1253,"date":"2019-06-29T11:49:16","date_gmt":"2019-06-29T14:49:16","guid":{"rendered":"https:\/\/felipeelia.com.br\/?p=1253"},"modified":"2019-07-04T19:52:48","modified_gmt":"2019-07-04T22:52:48","slug":"wordpress-rest-api-enable-random-order-of-posts-list","status":"publish","type":"post","link":"https:\/\/felipeelia.dev\/wordpress-rest-api-enable-random-order-of-posts-list\/","title":{"rendered":"WordPress REST API: Enable Random Order of Posts List"},"content":{"rendered":"\n
Some time ago, after announcing the WordPress 5.1 first beta on the WordPress Brasil Facebook group, a user asked when we’d have the option to random order the posts on WordPress REST API<\/a>. I explained that core doesn’t need to allow it because it could be done through a custom code.<\/p>\n\n\n\n The code below uses the filter<\/a> In order to apply the random order, you only have to call You only have to save the code as a PHP file and put it into the plugins directory. The code is also available as a gist<\/a>.<\/p>\n\n\n\n If you have any trouble deploying this code or with anything related to WordPress, give a look at my\u00a0Codeable Profile<\/a>\u00a0and click on that\u00a0Hire button<\/a>!<\/p>\n","protected":false},"excerpt":{"rendered":" A simple plugin to enable random order of the posts list on WordPress REST API<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_uag_custom_page_level_css":"","footnotes":""},"categories":[91],"tags":[102],"yoast_head":"\nrest_{$this->post_type}_collection_params<\/code> to include
rand<\/code> as an entry of the array which enumerates the possible values for ordination. This filter is used in the end of the
get_collection_params<\/code> method, inside the
WP_REST_Posts_Controller<\/code> class, as you can see here<\/a>. The
{$this->post_type}<\/code> filter part is variable and in the code I used it to change the posts<\/em> list.<\/p>\n\n\n\n
\/wp-json\/wp\/v2\/posts?orderby=rand<\/code>. If you’re using some cache solution, the final result can be affected.<\/p>\n\n\n\n
<?php\n\/**\n * Plugin Name: REST API - Post list randomize\n * Description: Randomize the content list in REST API passing `orderby=rand` as parameter.\n * Version: 1.0.0\n * Author: Felipe Elia | Codeable\n * Author URI: https:\/\/codeable.io\/developers\/felipe-elia?ref=qGTOJ\n *\/\n\n\/**\n * Add `rand` as an option for orderby param in REST API.\n * Hook to `rest_{$this->post_type}_collection_params` filter.\n *\n * @param array $query_params Accepted parameters.\n * @return array\n *\/\nfunction add_rand_orderby_rest_post_collection_params( $query_params ) {\n\t$query_params['orderby']['enum'][] = 'rand';\n\treturn $query_params;\n}\nadd_filter( 'rest_post_collection_params', 'add_rand_orderby_rest_post_collection_params' );<\/code><\/pre>\n\n\n\n
\n\n\n\n