How to force WordPress tag archives to include a custom post type

My mind is blown that #ChatGPT was able to create a (simple) #WordPress function for me that worked. #Mindblown. The #prompt Create a WordPress function that will force tag archives to show custom post types in addition to regular blog posts. The answer To force tag archives to display custom ...

How to force WordPress tag archives to include a custom post type with a function

My mind is blown that #ChatGPT was able to create a (simple) #WordPress function for me that worked. #Mindblown.

The #prompt

Create a WordPress function that will force tag archives to show custom post types in addition to regular blog posts.

The answer

To force tag archives to display custom post types along with regular blog posts in WordPress, you can use the pre_get_posts action hook to modify the main query. Here’s an example of a WordPress function that achieves this:

function custom_post_type_in_tag_archives($query) {
    if (is_tag() && $query->is_main_query()) {
        // Add your custom post type slug here
        $custom_post_type = 'your_custom_post_type';

        // Modify the query to include the custom post type
        $query->set('post_type', array('post', $custom_post_type));
    }
}
add_action('pre_get_posts', 'custom_post_type_in_tag_archives');

Replace 'your_custom_post_type' with the slug of your custom post type. For example, if your custom post type slug is books, you would replace 'your_custom_post_type' with 'books'.

Once you’ve added this code to your theme’s functions.php file or a custom plugin, the tag archive pages will display both regular blog posts and your specified custom post type.

Arp Laszlo
Hi, I’m Arp! I got diagnosed with ADHD at 49, and now I'm trying to figure out what's me, what's masking, and just about everything else. I make comics (when imposter syndrome isn't striking) and write about life as a creative Indian-American. I’m self-taught, self-employed, and self-flagellating.

More from the Blog

zapier wordpress

tl;dr: Is there a way to automate the creation of repetitive but slightly different products?

I’m looking for a way to automate creating & filling out products, ideally from a Google Sheet. Zapier does not seem to work with ...
How to force WordPress tag archives to include a custom post type with a function

How to force WordPress tag archives to include a custom post type

My mind is blown that #ChatGPT was able to create a (simple) #WordPress function for me that worked. #Mindblown. The #prompt Create a WordPress ...
Improving Calckey with Custom CSS

Improving Calckey with Custom CSS

I’ve been testing out #Calckey, because it has some extra features that #Mastodon doesn’t, like But some things about Calckey’s base #UserExperience really sucked: ...

Leave a Comment


This site uses Akismet to reduce spam. Learn how your comment data is processed.