简体   繁体   English

WP Rest API 通过带有特殊字符的 slug 发布(例如:!&')

[英]WP Rest API get post by slug with special characters (ex: !&')

I have posts with slugs with special characters.我有一些带有特殊字符的 slug 的帖子。 One of them is the following: http://localhost/wp-json/wp/v2/posts?slug=my-post !其中之一如下: http://localhost/wp-json/wp/v2/posts?slug=my-post

Unfortunately, WP REST API not showing the content since it has (!) within the slug.不幸的是,WP REST API 没有显示内容,因为它在 slug 中有(!)。

Is there any solution you guys would recommend?你们有什么解决方案可以推荐吗?

I have found the solution (at least for my case), not sure if it'll work for you but may indicate you the way to go.我找到了解决方案(至少对我而言),不确定它是否适合您,但可能会为您指明前进的道路。 We need to tap into the function used to sanitize the slugs, as I said in my comment, by default is wp_parse_slug_list .正如我在评论中所说,我们需要利用用于清理 slug 的函数,默认情况下是wp_parse_slug_list Looking at the code the function that actually sanitizes the slug is sanitize_title .查看代码,实际清理 slug 的函数是sanitize_title

Looking at the source code, wp_parse_slug_list calls sanitize_title with only one argument, which means that the context used is save .查看源代码, wp_parse_slug_list仅使用一个参数调用sanitize_title ,这意味着使用的上下文是save This means that, for posts that were already saved without being sanitized by this function, the slug won't match and the post will be inaccessible through the API.这意味着,对于未经此功能清理而已保存的帖子,slug 将不匹配,并且该帖子将无法通过 API 访问。 The solution is to change the sanitizing function slightly by adding a filter:解决方案是通过添加过滤器稍微改变消毒功能:

add_filter('rest_post_collection_params', function($query_params) {
    $query_params['slug']['sanitize_callback'] = 'sanitize_rest_api_slug';

    return $query_params;
}, 20, 1);

function sanitize_rest_api_slug( $list ) {
    if ( ! is_array( $list ) ) {
        $list = preg_split( '/[\s,]+/', $list );
    }

    foreach ( $list as $key => $value ) {
        $list[ $key ] = sanitize_title( $value, '', 'query' );
    }
    return array_unique( $list );
}

The filter is actually being applied on the function get_collection_params() on the class-wp-rest-posts-controller class, but if you look at the source code , the filter has a variable depending on the post_type , so if you have another special kind of posts defined (besides post ) you need to add/change a filter for that kind as well.过滤器实际上是应用于class-wp-rest-posts-controller类上的函数get_collection_params() ,但是如果您查看源代码,过滤器有一个取决于post_type的变量,因此如果您有另一个特殊定义的帖子类型(除了post )您还需要添加/更改该类型的过滤器。

I hope this helps somebody else like me, even if it's too late for your issue.我希望这可以帮助像我这样的其他人,即使对你的问题来说已经太晚了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM