Display Post by taxonomy and taxonomy child if exist

I have a registered Taxonomy called Types, which is hierarchical and works.
An example of categories will be
Hotel in UK
–1 star
–2 star
–3 star
Hotel in Spain
–1 star
–2 star
–3 star
etc..

I m having trouble finding the right way to display my pages (custom post Hotel).

Read More

I need the code to display hotels by taxonomy only if they exist

any help?

UPDATE CODE


 $taxonomy2 = 'accomodation-type';
 $termsacc = get_terms("accomodation-type",array('orderby' => 'slug', 'order' => 'ASC'));
   foreach ($termsacc as $termaccomodation) {
   //Here I loop through my tax acc-type
   //and check if there is any post by the country $termcountry->name (getting this value higher)
$query = new WP_Query(array('post_type' => 'accomodation', 'orderby'=> $termaccomodation->name,'order' => 'DESC','accomodation-type' =>$termaccomodation->name, 'country' =>$termcountry->name,'posts_per_page' => 48 ));

and loop....

Related posts

Leave a Reply

1 comment

  1. 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.