Created
January 24, 2022 01:45
-
-
Save shishirraven/9899390c644e0cda14725a1b30ed5f87 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
add_action( 'rest_api_init', 'addOrderbySupportRest' ); | |
function addOrderbySupportRest(){ | |
$post_type ="wf_account"; | |
// Add meta your meta field to the allowed values of the REST API orderby parameter | |
add_filter( | |
'rest_' . $post_type . '_collection_params', | |
function( $params ) { | |
$fields = ["first_name","last_name","address","email"]; | |
foreach ($fields as $key => $value) { | |
$params['orderby']['enum'][] = $value; | |
} | |
return $params; | |
}, | |
10, | |
1 | |
); | |
// Manipulate query | |
add_filter( | |
'rest_' . $post_type . '_query', | |
function ( $args, $request ) { | |
$fields = ["first_name","last_name","address","email"]; | |
$order_by = $request->get_param( 'orderby' ); | |
if ( isset( $order_by ) && in_array($order_by, $fields)) { | |
$args['meta_key'] = $order_by; | |
$args['orderby'] = 'meta_value'; // user 'meta_value_num' for numerical fields | |
} | |
return $args; | |
}, | |
10, | |
2 | |
); | |
} // addOrderbySupportRest function ends. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment