Display Post by taxonomy and taxonomy child

You should query all accomodation posts in this country, and then sort them by accomodation-type and region. Then you loop through the posts, and compare the accomodation type and the region of each post with those of the previous post. If they are different you print the new accomodation type or region and then print the post.

// Pseudo-code to explain the idea
$prev_post_accomodation_type = $accomodations[0]->accomodation_type;
$prev_post_region = $accomodations[0]->region;
echo '<ul>';
echo '<li>' . $prev_post_accomodation_type . '<ul>';
echo '<li>' . $prev_post_region . '<ul>';
foreach ( $accomodations as $accomodation ) {
    $cur_post_accomodation_type = $accomodation->accomodation_type;
    $cur_post_region = $accomodation->region;
    if ( $prev_post_accomodation_type != $cur_post_accomodation_type ) {
        echo '</ul></li>'; // Close previous region list
        echo '</ul></li>'; // Close previous accomodation type list
        echo '<li>' . $cur_post_accomodation_type . '<ul>';
        echo '<li>' . $cur_post_region . '<ul>';
    } elseif ( $prev_post_region != $cur_post_region ) {
        echo '</ul></li>'; // Close previous region list
        echo '<li>' . $cur_post_region . '<ul>';
    }
    echo '<li>' . $accomodation->post_title . '</li>';
}
echo '</ul></li>'; // Close previous region list
echo '</ul></li>'; // Close previous accomodation type list
echo '</ul>';

You can do this sorting in the database or in PHP. In PHP could be easier, but will require many extra database queries because you do get_post_terms() for each post. In the database is faster but will require some filtering of the SQL query that WordPress will execute.

My spelling corrector wants to replace accomodation with accommodation, is it too late to change this in your code too?

Leave a Comment