【问题标题】:Can't get WP_Query custom post type's category posts properly无法正确获取 WP_Query 自定义帖子类型的类别帖子
【发布时间】:2019-10-11 12:00:12
【问题描述】:

我对自定义帖子类型的 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


    【解决方案1】:

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

    $termsArray = explode(',', $attributes['postCategories']);
    
    $tax_query = array(
        array(
          'taxonomy' => 'my_cpt_category',
          'field'    => 'term_id',
          'terms'    => $termsArray
        )
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-11
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      相关资源
      最近更新 更多