Custom Post Type Loop with Query Var

Goal: Loop through custom post type (insurance products) and get only insurance types for that state based on a query var.

Post type: insurance_products

Taxonomies: state, insurer, insurance-type

I want to skip over the insurance type if the state does not have any insurance products for a product type.


As you can see there are insurance types that are empty, while the ones that are not contain the right data set.

My data set for this query is:


If feel like I am close but I could be way off.

    <div class="theme-page-wrapper mk-grid vc_row-fluid no-padding insurance">

    $insurance_types = get_terms('insurance-type');

    foreach($insurance_types as $insurance_type) {
        $args = array(
            'post_type' => 'insurance_products',
          'tax_query' => array(
                    'taxonomy' => 'insurance-type',
                    'field' => 'slug',
                    'terms' => $insurance_type->slug,

         $type_loop = new WP_Query($args);

         if($type_loop->have_posts()) {

            $state = get_query_var('state',FALSE);

            echo '<div class="ins-type-wrapper">';
            echo '<h2 class="ins-type-header ' . strtolower($insurance_type->name) . '">' . $insurance_type->        name . '</h2>';

            while($type_loop->have_posts()) : $type_loop->the_post();
            if (has_term( $state, 'state')) {
                    if (get_the_terms($post->ID, 'insurer') ) {
                    $taxonomy_ar = get_the_terms($post->ID, 'insurer');

                      $output = '<ul class="insurer-list">';
                      foreach ($taxonomy_ar as $taxonomy_term) {
                        $output .= '<li>'. $taxonomy_term->name .'</li>';
                      $output .= '</ul>';

                      echo $output;
            echo '</div>';


Hope I am clear enough, any help appreciated. As a side note I also considered hiding empty containers with jQuery but wasn’t sure if that was the best option.

Read more here: Custom Post Type Loop with Query Var

Leave a Reply

Your email address will not be published. Required fields are marked *