I'm requesting posts with the WP REST API and need to sort them according to an ACF field. It's value represents a date (numeric, jQuery date format yymmdd). I know how to do it with a normal WP_Query and tried to do the same using the rest api:
mydomain/wp-json/wp/v2/posts?filter[orderby]=meta_value_num&filter[meta_key]=my_field_name&filter[order]=DESC
In fact I'm using a custom post type that's registered with the rest api and everything else is working perfectly, so I think its not a cpt specific issue?
But the posts show up in default order (their creation date, latest to oldest). What am I missing? Is this orderby parameter not supported by the rest api? If so, how can I implement it myself?
Any other workarounds, suggestions? Really looking for a solution! Thankful for any hints!
I'm requesting posts with the WP REST API and need to sort them according to an ACF field. It's value represents a date (numeric, jQuery date format yymmdd). I know how to do it with a normal WP_Query and tried to do the same using the rest api:
mydomain/wp-json/wp/v2/posts?filter[orderby]=meta_value_num&filter[meta_key]=my_field_name&filter[order]=DESC
In fact I'm using a custom post type that's registered with the rest api and everything else is working perfectly, so I think its not a cpt specific issue?
But the posts show up in default order (their creation date, latest to oldest). What am I missing? Is this orderby parameter not supported by the rest api? If so, how can I implement it myself?
Any other workarounds, suggestions? Really looking for a solution! Thankful for any hints!
Share Improve this question asked Jan 2, 2017 at 15:39 Mauro BringolfMauro Bringolf 1772 silver badges7 bronze badges2 Answers
Reset to default 2I'm guessing you haven't exposed meta_key and meta_value to the REST API with the rest_query_vars filter, so this should do it:
function my_add_meta_vars ($current_vars) {
$current_vars = array_merge ($current_vars, array ('meta_key', 'meta_value'));
return $current_vars;
}
add_filter ('rest_query_vars', 'my_add_meta_vars');
Then you can refer to meta_key and meta_value in your query.
Be aware that this obviously exposes all your post metadata to the API, which has potential security implications; I believe that's why it's not activated by default.
add_filter( 'rest_post_query', function ( $args, $request ) {
if ( isset( $request['meta_key']) && !empty($request['meta_key'] ) ) {
$args['meta_key'] = $request['meta_key'];
}
return $args;
}, 10, 2);
add_filter( "rest_post_collection_params", function($query_params, $post_type){
array_push($query_params['orderby']['enum'],'meta_value' );
return $query_params;
}, 10, 2);