Tag.php not displaying posts with the tag

Ive got a CPT and in my CPT’s argument I am calling the taxonomy post_tag. When I create a tag.php file it doesn’t show any of the posts for said tag. My tag.php:

<?php get_header(); ?>

    <section class="row">
        <div class="col-md-7">
            <p>Tag: <?php single_tag_title(); ?></p>
            <?php if ( have_posts() ): while ( have_posts() ): the_post(); ?>
                <h1><?php the_title(); ?></h1>
            <?php endwhile;     
            else: ?>
                <p>not working</p>          
            <?php endif; ?>             
        </div>
        <?php get_sidebar(); ?>
    </section>

<?php get_footer(); ?>

In my research I ran across “tag.php doesn’t work with tags on a custom post type post?” but I am using what I thought was the default for tags post_tag. When I was referencing WP_Query() Tag Parameters it doesn’t show how to take into consideration for the tag clicked. When I search for tag.php I get Tag Templates and it doesn’t show any examples that take into consideration all tags. What is the proper way to write a WP_Query() for all posts pertaining to the tag? I did run across wp_get_post_tags() after some research and reading “WordPress get related pages (tag based) – wp_get_post_tags” but I’m not understanding the rewrite for tag.php and the codex has no examples. So how can I properly write my tag.php to return all posts for the clicked tag?

2 Answers
2

I figured it out thanks to Pieter’s comment:

In functions.php I added:

function tag_filter($query) {
  if ( !is_admin() && $query->is_main_query() ) {
    if ($query->is_tag) {
      $query->set('post_type', array( 'custom_post_type', ));
    }
  }
}
add_action('pre_get_posts','tag_filter');

Leave a Comment