How to add your new post type to WordPress category and tag archives

Out of the box, WordPress does not include custom post types in the archives for the default categories and tags archives. Because of this, you need to add the post types to the query yourself.

You will add the following snippets to your theme’s functions.php file or if you want, to a custom plugin build just for your own website.

Don’t want to worry about coding this yourself?

This is available via user interface with our premium CPTUI-Extended product.

Adding all CPTUI post types to the archives.

This example requires Custom Post Type UI 1.3.0+ due to cptui_get_post_type_slugs() function.

function my_cptui_add_post_types_to_archives( $query ) {
	// We do not want unintended consequences.
	if ( is_admin() || ! $query->is_main_query() ) {
		return;    
	}

	if ( is_category() || is_tag() && empty( $query->query_vars['suppress_filters'] ) ) {
		$cptui_post_types = cptui_get_post_type_slugs();

		$query->set(
			'post_type',
			array_merge(
				array( 'post' ),
				$cptui_post_types
			)
		);
	}
}
add_filter( 'pre_get_posts', 'my_cptui_add_post_types_to_archives' );

In this code, we check for if we’re on a category archive or a tag archive and if we’re not suppressing filters. If that’s all true, then we fetch an array of all CPTUI based post type slugs, and merge it into an array with the ‘post’ post type. With that array constructed, we pass it into the query parameters so that WordPress knows to query for all these post types.

Adding only some CPTUI post types to the archives.

function my_cptui_add_post_types_to_archives( $query ) {
	// We do not want unintended consequences.
	if ( is_admin() || ! $query->is_main_query() ) {
		return;    
	}

	if ( is_category() || is_tag() && empty( $query->query_vars['suppress_filters'] ) ) {

		// Replace these slugs with the post types you want to include.
		$cptui_post_types = array( 'my_post_type', 'my_other_post_type' );

		$query->set(
	  		'post_type',
			array_merge(
				array( 'post' ),
				$cptui_post_types
			)
		);
	}
}
add_filter( 'pre_get_posts', 'my_cptui_add_post_types_to_archives' );

This snippet will be very much like the first one, except we’re only including specific post types from CPTUI.

Make sure to change “my_post_type” and “my_other_post_type” to actually match your post type slugs that you want included.

Notes

If you only one either the category archive or the tag archive, then amend the second if statement like so:

if ( is_category() && empty( $query->query_vars['suppress_filters'] ) )

or

if ( is_tag() && empty( $query->query_vars['suppress_filters'] ) )
Updated Jan 17, 2023 5:39 PM