WordPressRESTAPI:如何检索由多个标记标记的帖子?
一些人使用WordPressRESTAPI:如何检索由多个标记标记的帖子?,wordpress,wp-api,Wordpress,Wp Api,一些人使用/posts?tags=tag\u id\u 1、tag\u id\u 2或/posts?tags[]=tag\u id\u 1&tags[]=tag\u id\u 2 但是wordpress似乎正在返回标记为tag1或tag2的帖子。我真正需要的是贴上tag1和tag2标签的帖子 有人有想法吗?我将与你分享我所做的事情 我为我的定制需求创建了一个新端点, 其结尾类似于myapi/v1/posts/tag1/tag2 add_action('rest_api_init', functi
/posts?tags=tag\u id\u 1、tag\u id\u 2
或/posts?tags[]=tag\u id\u 1&tags[]=tag\u id\u 2
但是wordpress似乎正在返回标记为tag1或tag2的帖子。我真正需要的是贴上tag1和tag2标签的帖子
有人有想法吗?我将与你分享我所做的事情 我为我的定制需求创建了一个新端点, 其结尾类似于
myapi/v1/posts/tag1/tag2
add_action('rest_api_init', function () {
register_rest_route( 'myapi/v1', 'posts/(?P<tag_1>[-\w]+)/(?P<tag_2>[-\w]+)',array(
'methods' => 'GET',
'callback' => 'get_posts_set'
));
});
添加操作('rest\u api\u init',函数(){
注册rest路由('myapi/v1','posts/(?P[-\w]+)/(?P[-\w]+)',数组(
'方法'=>'获取',
“回调”=>“获取帖子集”
));
});
然后,创建
function get_posts_set($request) {
$args = array(
'category_name' => $request['category_name'],
'tag_slug__and' => array( $request['tag_1'],$request['tag_2'] ),
);
$posts = get_posts($args);
if (empty($posts)) {
return new WP_Error( 'empty_category', 'there is no post in this category', array('status' => 404) );
}
// Following code is my processing of output. Customize it to suit your needs
$post_data = array();
$i = 0;
foreach( $posts as $post) {
$post_id = $post->ID;
$post_title = remove_html_comments($post->post_title);
$post_content = remove_html_comments($post->post_content);
$post_data[ $i ][ 'id' ] = $post_id;
$post_data[ $i ][ 'title' ] = $post_title;
$post_data[ $i ][ 'content' ] = $post_content;
$i++;
}
$response = new WP_REST_Response($post_data);
$response->set_status(200);
return $response;
}
function remove_html_comments($content = '') {
return preg_replace('/<!--(.|\s)*?-->/', '', $content);
}
函数get\u posts\u set($request){
$args=数组(
'category\u name'=>$request['category\u name'],
'tag_slug_和'=>数组($request['tag_1'],$request['tag_2']),
);
$posts=get_posts($args);
如果(空($员额)){
返回新的WP_错误('empty_category','this category'中没有post',array('status'=>404));
}
//以下代码是我对输出的处理。请自定义它以满足您的需要
$post_data=array();
$i=0;
foreach($posts作为$post){
$post_id=$post->id;
$post\u title=删除html\u注释($post->post\u title);
$post\u content=删除html\u评论($post->post\u content);
$post_data[$i]['id']=$post_id;
$post_data[$i]['title']=$post_title;
$post_数据[$i]['content']=$post_内容;
$i++;
}
$response=新的WP\u REST\u响应($post\u数据);
$response->set_status(200);
返回$response;
}
函数remove_html_comments($content=''){
返回preg_replace(“//”、“$content”);
}
这将只返回带有HTML格式的PostID、Post Title和Post内容,以便direcr重用。希望这能解决你的问题