• Skip to main content
  • Skip to secondary menu
  • Skip to primary sidebar
  • Skip to footer
SnippetPress

SnippetPress

The Home of WordPress Snippets

Vultr Web Hosting
  • Cheat Sheets
  • Reviews
  • Snippets
  • Tutorials

Limit the WordPress Search to Specific Post Types

June 16, 2020 by SnippetPress Leave a Comment

By default, WordPress will return all post types in its search results. If you need to limit the search results to specific post types, you can use the follwoing snippet:

add_filter( 'pre_get_posts', 'snippetpress_search_post_type' );
function snippetpress_search_post_type( $query ) {
	$post_types = array(
		'post',
		'page',
	);
    if ($query->is_search && !is_admin() ) {
        $query->set( 'post_type', $post_types );
    } 
	return $query;
}

The above snippet will limit the WordPress search results to Posts and Pages. Just change the $post_types array to include the post types that you need in your search results.

Where to add the snippet?

The snippet should be placed at the bottom of the functions.php file of your child theme. Make sure you know what you’re doing when editing this file. Alternatively, you can use a plugin such as Code Snippets to add the custom code to your WordPress site. If you need further guidance on how to add the code, check out our post on How to Add WordPress Snippets.

Filed Under: Snippets, Snippets, WordPress Core

Reader Interactions

Leave a Reply Cancel reply

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

Primary Sidebar

E-mail Newsletter

More to See

WooCommerce – Prevent Product Being Added To Cart If A Specific Product Is Already In Cart

July 15, 2020 By SnippetPress

WooCommerce – Display an “Add $X To Get Free Shipping” Notice

July 13, 2020 By SnippetPress

Footer

Recent

  • Change The WordPress Page Title Separator Without A Plugin
  • WooCommerce – Prevent Product Being Added To Cart If A Specific Product Is Already In Cart
  • WooCommerce – Display an “Add $X To Get Free Shipping” Notice
  • WooCommerce – Integrate Google Merchant Center Customer Reviews
  • WooCommerce – Disable Out of Stock Variations

Search

Copyright © 2023 ·SnippetPress