Skip to content

Instantly share code, notes, and snippets.

@timrross
Last active December 5, 2021 09:08
Show Gist options
  • Save timrross/e36a5a2083f4f73d8a6bfb32d27eef75 to your computer and use it in GitHub Desktop.
Save timrross/e36a5a2083f4f73d8a6bfb32d27eef75 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