Skip to content

Instantly share code, notes, and snippets.

@cgrymala
Created November 22, 2018 15:15
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 cgrymala/98093307c9f9c04664c98e82ab2458bf to your computer and use it in GitHub Desktop.
Save cgrymala/98093307c9f9c04664c98e82ab2458bf to your computer and use it in GitHub Desktop.
Allows you to use `rand` as an `orderby` parameter when querying a custom post type through the WordPress REST API
<?php
class Add_Rand_to_OrderBy {
public function __construct() {
add_action( 'rest_api_init', array( $this, 'rest_api_init' ) );
}
/**
* Set up any custom REST API handlers
*
* @access public
* @since 2.0
* @return void
*/
public function rest_api_init() {
$post_type_slugs = array( 'sponsor' );
foreach ( $post_type_slugs as $s ) {
add_filter( "rest_{$s}_collection_params", array( $this, 'rest_orderby_rand' ), 10, 1 );
}
/**
* Add rand as an orderby parameter for sponsor REST API queries
* @param array $params the array of parameters
*
* @access public
* @since 2.0
* @return array the updated array of parameters
*/
public function rest_orderby_rand( $params ) {
$params['orderby']['enum'][] = 'rand';
return $params;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment