How to show CPTs in term archive

I attached default taxonomy “category” to a “story” custom post type, when I register it:

  'show_in_rest' => true,
  'show_in_feed' => true,
  'taxonomies'   => ['category'],
  'has_archive'  => true,

Then, I try to show “story” posts with a category term using default template:

http://localhost:3000/category/my-term/

But the template only shows default posts instead CPT “story” AND default posts with that term.

How should the CPT “story” be included in the default wp_query in the term archive template?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can use pre_get_posts hook to modify the main query, or any WP_Query for that matter. For example like this,

add_action(
    'pre_get_posts',
    function($query) {
        // target only public category main query
        if (
            is_admin() ||
            ! $query->is_main_query() ||
            ! is_category()
        ) {
            return;
        }

        // include custom post type in the query
        $query->set( 'post_type', array( 'post', 'story' ) );
    }
);


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x