Created
November 22, 2018 15:15
-
-
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
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 | |
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