Display Post by taxonomy and taxonomy child if exist

I would use in this case two custom taxonomies:

  • hotel-country
  • stars

both none-hierarchical then your query would be as simple as for example hotel in uk with 2 stars:

$args = array(
    'post_type' => 'hotel',
    'tax_query' => array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'hotel-country',
            'field' => 'slug',
            'terms' => array( 'uk' ),
        ),
        array(
            'taxonomy' => 'stars',
            'field' => 'slug',
            'terms' => array( '3-stars' ),
        )
    )
);
$query_posts( $args );

Update:

Using your existing setup you can once again use 'tax_query' but you will need to now the child-taxonomy id, say:

UK
  3-stars - term_id = 32

then your query and args should be:

$args = array(
    'post_type' => 'hotel',
    'tax_query' => array(
        array(
            'taxonomy' => 'Types',
            'field' => 'id',
            'terms' => array( '32' ),
            'operator' => 'IN',
        )
    )
);
$query_posts( $args );

Update 2:

If you are already in the UK page then change you code to this:

$taxonomy2 = 'accomodation-type';
//the current page term id, (UK,JAPAN...)
$current_term_id = get_query_var('term_id');
//array of child terms IDs. 
$termchildren = get_term_children($current_term_id,$taxonomy2); 
$args = array(
    'post_type' => 'accomodation',
    'tax_query' => array(
        array(
            'taxonomy' => 'accomodation-type',
            'field' => 'id',
            'terms' => $termchildren,
            'operator' => 'IN',
        )
    )
);
$query( $args );
//loop 

this will get all posts of accomodation that have a accomodation-type child term of UK.

Leave a Comment