4

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.com/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!

2 Answers 2

2

I'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.

4
  • Thanks a lot, this is looking good. I will try it out. There might be a way to expose only certain meta_data? Anyways, this is the right direction. I was already debating sorting it myself after making the request. Jan 2, 2017 at 20:01
  • 1
    Might be; unsure beyond what I posted in my answer! Let me know what you find out.
    – iguanarama
    Jan 2, 2017 at 20:12
  • Just applied your suggestion and it works. Thank you! Jan 3, 2017 at 9:35
  • rest_query_vars is no longer a filter in current Wordpress.
    – Slavic
    Nov 23, 2018 at 12:49
0
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);
1
  • 1
    Thanks - does this do the same job as the existing answer? Can you explain why this is better than the accepted answer please?
    – Rup
    Sep 29, 2020 at 16:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.