首页 > 解决方案 > 无法正确获取 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。我究竟做错了什么?谢谢。

标签: wordpress

解决方案


您作为字符串而不是数组传递

$termsArray = explode(',', $attributes['postCategories']);

$tax_query = array(
    array(
      'taxonomy' => 'my_cpt_category',
      'field'    => 'term_id',
      'terms'    => $termsArray
    )
);

推荐阅读