wordpress - 无法正确获取 WP_Query 自定义帖子类型的类别帖子
问题描述
我对自定义帖子类型的 WP_Query 有一些问题,我无法正确按类别获取自定义帖子。我有:
function my_render_posts_block( $attributes ) {
$tax_query = array(
array(
'taxonomy' => 'my_cpt_category',
'field' => 'term_id',
'terms' => $attributes['postCategories']
)
);
$args = array(
'post_type' => 'my_cpt',
);
if($attributes['postCategories']) {
$args['tax_query'] = $tax_query;
}
$query = new WP_Query($args);
$posts = '';
if($query->have_posts()) {
$posts .= '<ul>';
while ($query->have_posts()) {
$query->the_post();
$posts .= '<li><a href="' . esc_url( get_the_permalink() ) . '">' . get_the_title() . '</a></li>';
}
$posts .= '</ul>';
wp_reset_postdata();
return $posts;
} else {
return '<div>' . __("No Posts Found", "my-blocks") . '</div>';
}}
实际上它适用于一个学期,但如果我选择 2 个学期,它只会显示第一个学期的帖子。在 $attributes['postCategories'] 我传递术语 ID,如果 var_dump 它我得到 string(7) "209,208",其中 209 和 208 是正确的术语 ID。我究竟做错了什么?谢谢。
解决方案
您作为字符串而不是数组传递
$termsArray = explode(',', $attributes['postCategories']);
$tax_query = array(
array(
'taxonomy' => 'my_cpt_category',
'field' => 'term_id',
'terms' => $termsArray
)
);
推荐阅读
- angular - 从 Angular dist 文件夹中检索所有丢失的 HTML 文件
- java - 带有 GUI 的二次公式只返回 NaN
- javascript - 无法向 Leaflet.js 热图添加点
- ios - 如何在编辑时根据 TextField 内容更改标签文本
- javascript - Uncaught (in promise) SyntaxError: json fetch 后输入意外结束
- javascript - 数据模板占位符的资源
- javascript - 使用 `apply` 更改排序功能
- mysql - 连接丢失服务器关闭连接 - 致命错误后无法排队查询
- angularjs - 自定义指令中的 AngularJS 表单在数据绑定后未更新
- javascript - 解析复杂的 CSS 字符串