Custom taxonomy template not working with simple loop. Multiple CPT using the same taxonomy

I need help with WP custom taxonomy and custom post types. I never find a working solution so far. Please accept my apologies if this has a simple solution. I tried my best to find solution everywhere first.

Explanation of issue –

  1. I have one taxonomy called “department”.
  2. I have 3 CPT called “course”, “faculty”, “library”.

All 3 CPT will use same taxonomy “department”. I have all setup successfully and assigned the “department” taxonomy to all 3 CPT.

Now I am trying to show posts (all 3 CPT posts) by “department” taxonomy terms (for instance, I have terms “x”,”y”,”z” for the taxonomy “department”). I have a template file called “taxonomy-department.php”, which has simple loop –

<?php if (have_posts()) : ?>

        <ul> 

        <?php while (have_posts()) : the_post(); ?> 
            <li>
                <?php the_title(); ?>
            </li>
        <?php endwhile; ?>

        </ul>
        <?php else : ?>

        <p><?php _e('Sorry, no posts matched your criteria.'); ?></p>

<?php endif; ?>

The above loop inside the taxonomy template, is not working and showing no posts. Just going to else statement. I am not sure how to achieve this.

If I fetch posts successfully (with your help), is it also possible to filter posts by CPT? (in the taxonomy template file)

Any help is much appreciated.

3 Answers
3

WP defaults to showing normal native Posts in archives. It won’t automagically pick up which post types you want in your archive.

You will have to adjust main query for it to explain that to it, with something like:

add_action( 'pre_get_posts', function ( WP_Query $query ) {

    if ( $query->is_main_query() && $query->is_tax( 'department' ) ) {
        $query->set( 'post_type', [ 'course', 'faculty', 'library' ] );
    }
} );

Leave a Comment