Custom post types are by default excluded from the main query except on taxonomy pages and custom post type archives.
You can simply use pre_get_posts
to correctly alter the main query (alter the query variables before the SQL query is build and executed) to your needs.
Just a few notes on pre_get_posts
-
pre_get_posts
runs front end and back end queries, so it is very important to do theis_admin()
check for queries only meant to run front end or back end -
pre_get_posts
alters all custom instances ofWP_Query
,get_posts()
(which usesWP_Query
) and the main query (which also usesWP_Query
). You would want to use theis_main_query()
check to specifically only alter the main query.
You can do the following in a plugin or your theme’s functions.php
add_action( 'pre_get_posts', function ( $q )
{
if ( !is_admin() // Only target front end queries
&& $q->is_main_query() // Only target the main query
&& $q->is_category() // Only target category archives
) {
$q->set( 'post_type', ['post', 'custom_post_type'] ); // Adjust as needed
}
)};