2

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?

1
  • 2
    Use pre_get_posts to add your cpt to the main query on tag pages Sep 20, 2015 at 18:21

2 Answers 2

7

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');
1
  • This kills the tag.php query in my case.
    – Floris
    Mar 21, 2019 at 15:10
2

This worked perfectly for me. I also wanted to include other post types, so I added:

$query->set('post_type', array( 'custom_post_type', 'post', 'page' ));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.