Exclude Posts Pages or Specific Post from Search Result in WordPress

Hello WordPress Developer
Sometime you may have requirement or your client requested to exclude specific post, page fro WOrdpress search result or completely Exclude Posts or Pages or Custom post type records from search result and display search records only records from specific post type like Posts or Pages or CPT than you can achieve it by adding following few line code in your active theme fucntions.php file

function ls_search_filter( $query ) {
     if ( ! $query->is_admin && $query->is_search && $query->is_main_query() ) {
	  $query->set('post_type', array('page') ); // Search Result only from pages
          //$query->set('post_type', array('post') ); // Search Result only from posts
	  //$query->set('post__not_in', array(1,11)); // Exclude Post ID 1 & 11 from result 
add_action('pre_get_posts', 'ls_search_filter' );
Scroll to Top