WP REST API: Order posts by meta value (acf)?

WordPress Development Asked by Mauro Bringolf on December 9, 2020

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:[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

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.

Correct answer by iguanarama on December 9, 2020

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);

Answered by Amjad on December 9, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP