我正在尝试按值筛选我的Custom post类型分类法,但没有成功。
我想知道是否有其他人知道你会怎么做,或者也许我在这里采取了错误的方法?
感谢
您是否试图通过分类术语值筛选您的自定义帖子类型?例如,你有一个post-type"book"和一个分类法"book_cat",并且你想从一个特定的book_cat中获取所有的书,对吗?
WP REST API本机支持按分类术语ID进行筛选
你可以像一样提出GET请求
https://example.com/wp-json/wp/v2/book?book_cat=20
如果需要选择多个术语,请用逗号将它们隔开。
https://example.com/wp-json/wp/v2/book?book_cat=20,21,22
(https://example.com/wp-json/wp/v2/<post_type>?<taxonomy_name>=<term_id>,<term_id>
(
就是
编辑:实际上你不能过滤后类型的条款段塞,你需要使用id
如果你需要通过term_slug获取term_id,你可以这样做:
$term = get_term_by('slug', 'my-term-slug', 'my_taxonomy')
$term_id = $term->term_id;
您可以使用自定义过滤器将术语段塞用作参数
如果你真的需要使用slug作为url参数,你可以添加一个自定义过滤器,看看rest_{$this->post_type}_query hook
你可以这样做:
/**
* Filter book post type by book_cat slug
*
* @param array $args
* @param WP_Rest_Request $request
* @return array $args
*/
function filter_rest_book_query( $args, $request ) {
$params = $request->get_params();
if(isset($params['book_cat_slug'])){
$args['tax_query'] = array(
array(
'taxonomy' => 'book_cat',
'field' => 'slug',
'terms' => explode(',', $params['book_cat_slug'])
)
);
}
return $args;
}
// add the filter
add_filter( "rest_book_query", 'filter_rest_book_query', 10, 2 );
然后
https://example.com/wp-json/wp/v2/book?book_cat_slug=slug01,slug02
您可以在post查询中传递tax_query,如下所示:
$tax_query[] = array(
'taxonomy' => 'product_cat',
'field' => 'tag_ID', // Filter by Texonomy field name tag_ID
'terms' => $termID, // your texonomy by which you want to filter
);
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'tax_query' => $tax_query,
);
$loop = new WP_Query($args);
此外,您还可以通过分类slug进行过滤:-
$tax_query[] = array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $slugID
);