WordPress REST API URL解码 [英] Wordpress REST API url decoding

查看:187
本文介绍了WordPress REST API URL解码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在尝试使用jQuery向REST API(wordpress)发出请求.由于编码原因:

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

成为这个:

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

修改

这是我准备请求的方式:

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

推荐答案

我找到了解决方案. WordPress已自动解码网址.但是,我发现自WordPress 4.7起,随着WP API v2的实施,过滤查询var被删除.因此,我只需要将此代码段添加到我的functions.php文件中就可以了.

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

这篇关于WordPress REST API URL解码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆