Get Posts Under Custom Taxonomy

  • I am not getting the posts under custom taxonomy(fabric_building_types). I am getting cat_id and cat->name also but not able to get the posts.

    $args = array(
        'type'                     => 'post',
        'child_of'                 => 0,
        'parent'                   => '',
        'orderby'                  => 'name',
        'order'                    => 'ASC',
        'hide_empty'               => 1,
        'hierarchical'             => 1,
        'exclude'                  => '',
        'include'                  => '',
        'number'                   => '',
        'taxonomy'                 => 'fabric_building_types',
        'pad_counts'               => false 
    ); 
    
    $categories = get_categories( $args );
    
    foreach ( $categories as $cat ) {
    
        // here's my code for getting the posts for custom post type
    
        $posts_array = get_posts(
            array(
                'showposts' => -1,
                'post_type' => 'fabric_building',
                'tax_query' => array(
                    array(
                        'taxonomy' => 'fabric_building_types',
                        'field' => $cat->cat_ID,
                        'terms' => $cat->name,
                    )
                )
            )
        );
        print_r( $posts_array ); 
    }
    

    Can anyone please help me out...Thanks in advance

    valid values for `field` in a tax query are `term_id`, `name`, or `slug`.

  • Milo

    Milo Correct answer

    6 years ago

    Your tax query is incorrect, field should be the field you want to query on: term_id, name, or slug -

    $posts_array = get_posts(
        array(
            'posts_per_page' => -1,
            'post_type' => 'fabric_building',
            'tax_query' => array(
                array(
                    'taxonomy' => 'fabric_building_types',
                    'field' => 'term_id',
                    'terms' => $cat->term_id,
                )
            )
        )
    );
    

    how to paginate this posts after get their?

License under CC-BY-SA with attribution


Content dated before 6/26/2020 9:53 AM