Question

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?

Was it helpful?

Solution

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' ) );
    }
);
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top