1. WordPress Snippets

How to Include Custom Post Types in WordPress Search Results

The WordPress default search doesn’t include a custom post type in search results.so if you need to include a custom post type you can modify the query with pre_get_posts in just one minute using this code snippet.

Steps to include custom post types:

  1. Open the WordPress admin panel then go to Appearance > Theme Editor
  2. Open theme functions.php file, if you work localhost open the same file using any code editor IDE
  3. Add the following code at the bottom of the file.
  4. Save the changes.
function zytheme_include_cpt_search_results( $query ) {
    if ( $query->is_main_query() && $query->is_search() && ! is_admin() ) {
        $query->set( 'post_type', array( 'post', 'page', 'custom_post_type' ) );
    }
}
add_action( 'pre_get_posts', 'zytheme_include_cpt_search_results' );

Did you find the WordPress snippets in this article helpful? Share it with your friends and if you have any questions and want to ask us about it, please don’t hesitate to add comments.

Comments to: How to Include Custom Post Types in WordPress Search Results

Your email address will not be published. Required fields are marked *