Ensuring your post type posts show in search results.

Out of the box, WordPress does not include custom post types in the search results. 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 search results.

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

<?php
function my_cptui_add_post_type_to_search( $query ) {
	if ( is_admin() ) {
		return;
	}

	if ( $query->is_search() ) {
		$cptui_post_types = cptui_get_post_type_slugs();
		$query->set(
			'post_type',
			array_merge(
				array( 'post' ), // May also want to add the "page" post type.
				$cptui_post_types
			)
		);
	}
}
add_filter( 'pre_get_posts', 'my_cptui_add_post_type_to_search' );

In this code we check to see if WordPress is performing a search. If that’s 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 in it all into the query parameters so that WordPress knows to query within them all.

Adding only some CPTUI post types to the search results.

<?php
function my_cptui_add_post_type_to_search( $query ) {
	if ( $query->is_search() ) {
		// 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_type_to_search' );

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

Updated Jan 17, 2023 5:53 PM