如何获得 WP-API 类别的帖子列表?
How can I get a list of posts for a category with WP-API?
应该很容易,但是在WP-API docs里没找到。
找到了,有点[隐藏][1]
使用类别名称:
/posts?categories=1
试试这个。
对于类别名称,应添加两个过滤器,如下所示:
add_filter( "rest_post_query", function( $args, $request){
if ( isset( $request['category_name']) && !empty($request['category_name'] ) ) {
$args['category_name'] = $request['category_name'];
}
return $args;
}, 10, 2);
add_filter( "rest_post_collection_params", function($query_params, $post_type){
$query_params[ 'category_name' ] = array(
'description' => __( 'Category name.' ),
'type' => 'string',
'readonly' => true,
);
return $query_params;
}, 10, 2);
这个例子 url 对我有用... https://yourdomain.com/?rest_route=/wp/v2/posts&categories=99
此问题与 this other question here from the forum
重复
http://example.com/wp-json/wp/v2/posts?categories=20,30
以上将从category 20 OR category 30
return posts
我已经使用自定义 post 类型进行了测试,它也能完美运行
回复和致谢归功于“Manish Jung Thapa”
这段代码对我有用
Add to your function.php
function rest_filter_by_custom_taxonomy( $args, $request ) {
if ( isset($request['category_slug']) )
{
$category_slug = sanitize_text_field($request['category_slug']);
$args['tax_query'] = [
[
'taxonomy' => 'category',
'field' => 'slug',
'terms' => $category_slug,
]
];
}
return $args;
}
add_filter('rest_post_query', 'rest_filter_by_custom_taxonomy', 10, 3);
EX: /wp-json/wp/v2/posts?category_slug=news
应该很容易,但是在WP-API docs里没找到。
找到了,有点[隐藏][1]
使用类别名称:
/posts?categories=1
试试这个。
对于类别名称,应添加两个过滤器,如下所示:
add_filter( "rest_post_query", function( $args, $request){
if ( isset( $request['category_name']) && !empty($request['category_name'] ) ) {
$args['category_name'] = $request['category_name'];
}
return $args;
}, 10, 2);
add_filter( "rest_post_collection_params", function($query_params, $post_type){
$query_params[ 'category_name' ] = array(
'description' => __( 'Category name.' ),
'type' => 'string',
'readonly' => true,
);
return $query_params;
}, 10, 2);
这个例子 url 对我有用... https://yourdomain.com/?rest_route=/wp/v2/posts&categories=99
此问题与 this other question here from the forum
重复http://example.com/wp-json/wp/v2/posts?categories=20,30
以上将从category 20 OR category 30
我已经使用自定义 post 类型进行了测试,它也能完美运行
回复和致谢归功于“Manish Jung Thapa”
这段代码对我有用
Add to your function.php
function rest_filter_by_custom_taxonomy( $args, $request ) {
if ( isset($request['category_slug']) )
{
$category_slug = sanitize_text_field($request['category_slug']);
$args['tax_query'] = [
[
'taxonomy' => 'category',
'field' => 'slug',
'terms' => $category_slug,
]
];
}
return $args;
}
add_filter('rest_post_query', 'rest_filter_by_custom_taxonomy', 10, 3);
EX: /wp-json/wp/v2/posts?category_slug=news