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 Made for WordPress   /   Ready for your story

Ready to Build?

Your next great website starts here.

Build more websites with one flexible collection—and keep every theme for life.

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

The complete collection

$75

One payment. No renewals.

Get the Themes Bundle — $75