How to show CPTs in term archive
-
26-04-2021 - |
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?
La 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' ) );
}
);
Licencié sous: CC-BY-SA avec attribution
Non affilié à wordpress.stackexchange