无法正确获取WP_Query自定义帖子类型的类别帖子

时间:2019-10-11 12:00:12

标签: wordpress

我对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。 我究竟做错了什么? 谢谢。

1 个答案:

答案 0 :(得分:0)

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

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

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