0
votes

I have some problem with WP_Query for custom post types, I can't get custom posts by categories properly. I have:

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>';
}}

Actually it's working for one term, but if I choose 2 terms, it will show posts only for first term. In $attributes['postCategories'] I pass terms ids, if var_dump it I get string(7) "209,208", where 209 and 208 are correct ids of terms. What am I doing wrong? Thanks.

1

1 Answers

0
votes

You passed as a string instead of an array

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

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