November 15, 2014 - How to, Tech-Admin

Hiding pages from search results

On InsideLaw, pages can be hidden from appearing in the built-in WordPress search results by adding the id# of the page/post to a comma-separated list in the site settings.

First, you need the post number (post=####)  that can be found in the URL of the edit page for that post.

When logged in as a super-admin, the admin toolbar menus "My Sites / Network Admin / Sites" brings up a list of sites. Select "Edit" for the site containing the post to hide. On the "Settings" tab, find the "Exclude From Search" entry. Add the post number to the list with a comma and no spaces.

The page will no longer show up in the internal search results, but will still show up in searches from external search engines (e.g. Google or Bing) if the page is publically accessible.

Technical details

This exclusion is implemented in the theme "function.php" via:

// remove certain pages from search results
// IDs of pages can be entered in via "Site/Edit" "Settings" tab entry "Exclude From Search"
// ref: http://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts

function exclude_from_search($query) {
	if ( !is_admin() && $query->is_main_query() ) {
		if ($query->is_search) {
			$exclude_list = get_option('exclude_from_search');
			if ($exclude_list) {
				$exclude_ids = explode(',', $exclude_list);
				$query->set('post__not_in', $exclude_ids);
			}
		}
	}
}

add_action('pre_get_posts','exclude_from_search');

Comments are closed.