Exclude Specific Posts/Pages from the WordPress Search


Categories
Tags
On occasion you might want to exclude certain pages or posts from the search page on your WordPress site. Learn how to do this with just a little bit of code.

Photo by Matthew Henry on BURST

Pretty straightforward this one.

Just amend this with the ID’s of the posts/pages that you’d like to exclude from your site’s search page and add it to your functions.php file.

//Exclude pages/posts from site search (e.g. calendar embeds)
add_filter( 'pre_get_posts' , 'search_exc_pages' );

function search_exc_pages( $query ) {
	if( $query->is_admin )
		return $query;
	if( $query->is_search ) {
		$query->set( 'post__not_in' , array( 1,2,3,4,5 ) ); // Page IDs
		$query->set( 'category__not_in' , array( 1,2,3 ) ); // Category IDs
	}	return $query;
}   

Comments

Whether you have feedback, a question, want to share your opinion, or simply want to say thank you - we welcome comments! Please read the disclaimer.

Disclaimer and Legal Information

The use of any content found on or via this website (code, how to guides etc.) is done so at your own risk. We take no responsibility for any issues encountered.

This blog and its authors will not be held responsible for any misuse, reuse, recycled and cited/uncited copies of content from this website by others.

The views and opinions expressed in this blog are those of the author(s) and do not necessarily reflect the position or opinion of any other agency, organisation, employer or company.

Comments are moderated but we do not take any responsibility for any libel or litigation that results from something written in a comment. We reserve the right to reject or delete any comment for any reason whatsoever (abusive, profane, rude etc). Please keep your comments polite and relevant.

We are happy for you to quote and share our content in any reasonable manner, e.g. post links to our blogs on social media, but not in any way that suggests that we, or our authors, endorse you, your use or your views. Nothing negative please.

We appreciate attributions, e.g. a link to our website (www.dragoncode.co.uk).

Thank you – we hope you find the website useful.