Post Pic

Wordpress Tips: Excluding Pages/Posts From Searches

Sometimes you just don’t want certain pages, or posts to appear when a user searches your WordPress blog. Here is a quick & easy tip to rid your search results of those pesky posts/pages, plus an extra tip to remove pages completely.

It’s very, very easy to remove certain posts, and/or pages from your search results. Although I guess it’s only really easy if you know how, so instead of keeping it all hush, hush here is the secret.

Where Does It Go?

These code snippets would be placed in search.php, if that file is not there then searches will use your index.php file. Should the latter be true you will need to limit the code to running only when a search is being made. To do that use the following bit of code.

if(is_search()) {
	//code snippet here...
}

Keeping Wordpress’ Default Query

The big problem most people have is that they must keep WordPress’ default query intact or the search results will be destroyed when you create your new query. This is actually documented on the codex, but I’ll try to simplify it a bit more:

query_posts(
	array_merge(
		array('option' => 'value'),
		$wp_query->query
	)
);

This takes your new options in array format & merges them with the original WordPress query, that keeps your search results intact but adds in your options.

Excluding Pages & Posts

We can now use this to exclude any pages & posts we want. First write yourself a list of all of the ID’s of the posts/pages you want to exclude. Then add them to your code like so:

query_posts(
	array_merge(
		array('post__not_in' => array(1,2,3,4,5)),
		$wp_query->query
	)
)

Although it does say post__not_in it does exclude both posts & pages.

Excluding All Pages

Of course there is also the possibility that you do not want to show any pages at all, a good example is if you run a blog & your pages are just for things like about us, privacy policy & disclaimers. You can do that simply by telling the query to only retrieve posts.

query_posts(
	array_merge(
		array('post_type' => 'post'),
		$wp_query->query
	)
)

Well that’s it. I hope this tip has helped you or inspired you in some way. If you have any questions drop me a comment or send me a email & I’ll help you asap.

One Response

Leave a Response

Please enclose code in [lang] tags. For example [php] echo 'hello world'; [/php]

* Name, Email, Comment are Required

£53.06 / £1200

Help me buy an iMac so I can develop iPhone/iPod apps. If you would like to donate, or you want to learn more about why I started this fund click here.

We're Talking About...