How to get the posts of a custom taxonomy term

I hope someone will help me:

I have a Custom Post Type (Movie) with its custom taxonomy (Producer), this taxonomy has its own terms, for example ‘WarnerBros’.

How I can get all the posts of my term (WarnerBros)?

I have this but doesn’t work yet.

$args = array(
   'post_type' => 'movie',
    'tax_query' => array(
        array(
            'taxonomy' => 'producer',
            'field'    => 'slug',
            'terms'    => 'WarnerBros',
        ),
    ),
);
$query = new WP_Query( $args );

After playing with the code I resolved the problem, I will share my code for someone with the same issue:

 
$type="Movie";  // Custom Post Type Name
$tag =  'WarnerBros'; // Your Term

$args = array( 'post_type' => $type, 'paged' => $paged, 'posts_per_page' => -1, 'orderby' => 'menu_order', 'order' => 'ASC', 'tax_query'=>array( array( 'taxonomy'=>'Producer', //Taxonomy Name 'field'=>'slug', 'terms'=>array($tag) )) );

$loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); if(is_object_in_term($post->ID,'Taxonomy_Name','Your_Term')) // Producer and WarnerBros {

echo '<div id="YourID">'; echo the_title(); echo '</div>'; } endwhile;

3 s
3

This question has different answers in this specific WordPress question, they may be of help:

Display all posts in a custom post type, grouped by a custom taxonomy

Personally I used this method that worked for me just fine:

$terms = get_terms('tax_name');
$posts = array();
foreach ( $terms as $term ) {
    $posts[$term->name] = get_posts(array( 'posts_per_page' => -1, 'post_type' => 'post_type', 'tax_name' => $term->name ));
}

Editing it to your scenario this should work:

$terms = get_terms('producer');
$posts = array();
foreach ( $terms as $term ) {
    $posts[$term->name] = get_posts(array( 'posts_per_page' => -1, 'post_type' => 'movie', 'tax_name' => $term->name ));
}

Now you can get your posts:

print_r($posts["WarnerBros"]);

Leave a Comment