Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save atultiwari/7cc5b980a216e6817c5aef9aad35482b to your computer and use it in GitHub Desktop.
Save atultiwari/7cc5b980a216e6817c5aef9aad35482b to your computer and use it in GitHub Desktop.
<?php
/**
* Check the orderby param for the particular REST API for hte custom post type.
* If it is set to a particular meta_ket, then set the orderby and meta_key query args/
* @link https://www.timrosswebdevelopment.com/wordpress-rest-api-order-by-meta_value/
*/
function filter_rest_accommodation_query($query_vars, $request) {
$orderby = $request->get_param('orderby');
if (isset($orderby) && $orderby === 'number_of_beds') {
$query_vars["orderby"] = "meta_value_num";
$query_vars["meta_key"] = "number_of_beds";
}
return $query_vars;
}
// The filter is named rest_{post_type}_query. So you need to hook a new filter for each
// of the custom post types you need to sort.
add_filter( 'rest_accommodation_query', 'filter_rest_accommodation_query', 10, 2);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment