Wordpress REST API url decoding

2019-09-16 17:14发布

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

1条回答
劳资没心,怎么记你
2楼-- · 2019-09-16 17:52

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);
查看更多
登录 后发表回答