0

So I’m trying to use jQuery to make requests to a REST API (wordpress). Due to encoding this:

http://localhost:8040/?rest_route=/wp/v2/posts&filter[meta_key]=holiday_type&filter[meta_value]=villa

becomes this:

http://localhost:8040/?rest_route=%2Fwp%2Fv2%2Fposts&filter%5Bmeta_key%5D=holiday_type&filter%5Bmeta_value%5D=villa&

Thus resulting in wrong results. Is there a setting I could change or a I can override to handle. If so, which controller should I extend? The documentation is not that exhaustive

Edit

This is how I prepare the request:

$.get('/', {
        'rest_route': '/wp/v2/posts',
        'filter[meta_key]': 'holiday_type',
        'filter[meta_value]': holidayType
    }).done(function(data) {
         // do processing
    })
4
  • what is the error you get ? If there is a mistake it probably lies in the first request. Does it work without encoding ? Commented Aug 1, 2017 at 15:53
  • Show how you create the requests as per minimal reproducible example Commented Aug 1, 2017 at 16:27
  • @Unex I don't get an error, just all the results because the filters and being processed. It works without the encoding. jQuery encodes all requests and also the browser Commented Aug 1, 2017 at 16:41
  • @charlietfl I've added the info. Commented Aug 1, 2017 at 16:46

1 Answer 1

0

I found the solution. Wordpress already decodes urls automatically. I discovered however that the filter query var was removed as of wordpress 4.7 with the implementation of WP API v2. So I just need this snippet of code to my functions.php file and it worked.

add_filter('rest_post_query', function ($args, $request) {
    if ( empty( $request['filter'] ) || ! is_array( $request['filter'] ) ) {
        return $args;
    }

    $filter = $request['filter'];

    if ( isset($filter['meta_key']) &&  isset($filter['meta_value'])) {
        $args['meta_key'] =  $filter['meta_key'];
        $args['meta_value'] =  $filter['meta_value'];
    }

    if ( isset( $filter['posts_per_page'] ) && ( (int) $filter['posts_per_page'] >= 1 && (int) $filter['posts_per_page'] <= 100 ) ) {
        $args['posts_per_page'] = $filter['posts_per_page'];
    }
    global $wp;
    $vars = apply_filters( 'query_vars', $wp->public_query_vars );
    foreach ( $vars as $var ) {
        if ( isset( $filter[ $var ] ) ) {
            $args[ $var ] = $filter[ $var ];
        }
    }

    return $args;
}, 10, 2);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.