Including custom post types in search results allows you to make all relevant content on your site easily accessible to users. It can enhance your site's search functionality and user experience. By default, WordPress search results only include posts from the standard "post" post type. If you have custom post types on your site and want them to be searchable, you can easily achieve this using the "pre_get_posts" hook.
Suppose you have a custom post type called "recipes", and you want it to appear in search results alongside regular posts. You can do this by adding the following code to your themes's functions.php file:
function themesdna_add_custom_post_types_to_search( $query ) {
// Check if it's the main search query and not in the admin area
if ( $query->is_search() && $query->is_main_query() && !is_admin() ) {
// Include the 'recipes' post type in search results
$query->set( 'post_type', array( 'post', 'recipes' ) );
}
}
add_action( 'pre_get_posts', 'themesdna_add_custom_post_types_to_search' );