我正在创建简单的API端点,以获取具有指定类别和标记的自定义post类型项。
function my_awesome_func( $data ) {
$posts = get_posts( array(
\'post_type\' => \'faq\',
\'numberposts\' => 10,
\'tax_query\' => array(
\'relation\' => \'AND\',
array(
\'taxonomy\' => \'category\',
\'field\' => \'slug\',
\'terms\' => array($data[\'cat\'])
),
array(
\'taxonomy\' => \'post_tag\',
\'field\' => \'slug\',
\'terms\' => array($data[\'tag\'])
),
)
)
);
if ( empty( $posts ) ) {
return null;
}
foreach( $posts as $post ) {
$id = $post->ID;
$posts_data[] = (object) array(
\'id\' => $id,
\'title\' => $post->post_title,
\'content\' => $post->post_content
);
}
return $posts_data;
}
add_action( \'rest_api_init\', function () {
register_rest_route( \'test/v1\', \'/faq/cat=(?P<cat>[a-zA-Z0-9_,]+)/tag=(?P<tag>[a-zA-Z0-9_,]+)\', array(
\'methods\' => \'GET\',
\'callback\' => \'my_awesome_func\',
) );
} );
它可以很好地处理此请求:
...wp-json/test/v1/faq/cat=cars/tag=big
但我想通过只添加类别或标签,使其更加灵活
...wp-json/test/v1/faq/cat=cars
并通过添加多个标记(即用逗号分隔):
...wp-json/test/v1/faq/cat=cars/tag=big,blue
提前感谢您的帮助。