0
votes

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

function my_blocks_render_function( $attributes ) {

$args = array(
    'post_type' => 'my_cpt',
    'posts_per_page' => $attributes['numberOfPosts']
);
if($attributes['postCategories']) {
    $args['cat'] = $attributes['postCategories'];
}
$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>';
}}

With 'post_type'=>'post', everything working correctly, but with custom post types nothing. If postTypes weren't chosen I'm getting all custom posts, but If were "No Posts Found".

What am I doing wrong? I've tried to add tax_query, but the same result. And I var_dump my postCategories and getting correct ids.

Sorry for my English, thanks.

1

1 Answers

2
votes

This will work correctly.

$taxonomy='our_project_category';
$tax_terms = get_terms($taxonomy, array('hide_empty' => false));
foreach($tax_terms as $term_single) {      
$categories_id= 2; //category_id  

 $args_new  =  array(
  'post_type' => 'our-project',
  'posts_per_page' => 6,
  'tax_query' => array(
    array(
      'taxonomy' => 'our_project_category',
      'field'    => 'term_id',
      'terms'    => $categories_id,
    ),
  ),
);
$loop_new = new WP_Query($args_new);

if($loop_new->have_posts()) {
while($loop_new->have_posts()) : $loop_new->the_post();

//content

endwhile; wp_reset_query();
    endif;
    ?>