How to Add Custom Post Types to Search Results in WordPress

By ThemesDNA1 min read

Share:

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' );
Premium WordPress themes One-time payment   /   Lifetime updates

Ready to Build?

Get the ThemesDNA bundle.

Get all premium ThemesDNA themes with lifetime updates and unlimited website usage for a one-time payment.

  • 56 premium themes
  • Lifetime updates
  • Unlimited websites
  • No renewals

The complete premium theme bundle

$75

One payment. No renewals.

Get the ThemesDNA Bundle — $75