Custom Post Type showing even when taxonomy is blank

150 views Asked by At

I am using Custom Post Type to get its contents by using Custom Taxonomy in different pages.

However, the contents are being displayed even if the post type has no taxonomy.

P.S. I am using ACV as well to get the fields of Taxonomy

Here's the code:

<?php if( get_field('review_category_name') ):
    $taxonomy_slug = get_field('review_category_name');  //Advanced Custom Field here
 endif; ?>
<?php $args = array( 'post_type' => 'reviews','tax_query' => array(
        'taxonomy' => 'reviews_category',
        'field' => 'slug',
        'terms' => $taxonomy_slug,
    ), 'posts_per_page' => 5 );
        $loop = new WP_Query( $args ); ?>
<div class="">
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
    <h3><?php the_title(); ?></h3>
    <?php the_content(); ?>
</div>
<?php endwhile; ?>

Am I missing anything here?

$taxonomy_slug is a variable to get the custom post type slug.

1

There are 1 answers

0
janw On BEST ANSWER

Wrap everything in the get_field('review_category_name') if check:

<?php if( get_field('review_category_name') ): ?>
<?php
    $taxonomy_slug = get_field('review_category_name');  //Advanced Custom Field here
    $args = array( 'post_type' => 'reviews','tax_query' => array(
            'taxonomy' => 'reviews_category',
            'field' => 'slug',
            'terms' => $taxonomy_slug,
    ), 'posts_per_page' => 5 );
    $loop = new WP_Query( $args );
?>
<div class="">
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
    <h3><?php the_title(); ?></h3>
    <?php the_content(); ?>
</div>
<?php endwhile; ?>
<?php endif; ?>

PS your example was missing the endwhile