By default, WordPress includes every post types on its search results pages. That includes, posts, attachments, pages and others. For example, if one searches for the term ‘Wordpress’ on a WordPress site, which has the default settings, all post types that include the word ‘Wordpress’ will show up on the search result pages.

This may not be the best way to display search results on your site. It can be confusing to someone who’s just trying to get the right information as quickly as possible.

This post is going to show you how to limit the search result pages to include only posts and not images or attachments.

I had this  particular problem on this site few weeks ago. If you had searched for a particular topic weeks ago, this result page would’ve included posts, images, and other non essential post elements.

This really messed up my result pages. So I changed it. Now you’ll only get posts that are related to the search terms when you search for help on this blog.

If you have the same problem on your site, continue below to learn how to.

What you’ll need to do is add this blog of code to the theme’s function.php page. This file is mostly located at /….wp-content/themes/your_theme/function.php.

add_action( 'init', 'exclude_from_search' );
function exclude_from_search() {
  global $wp_post_types;
  /* Exclude 'page' post type. */
  $wp_post_types['page']->exclude_from_search = true;
  /* Exclude 'attachment' post type. */
  $wp_post_types['attachment']->exclude_from_search = true;


Save the file and you’re done. You may have to restart Apache or Nignx web servers for the changes to take effect.

That’s it!

The code above will exclude WordPress pages, and attachment (images) from its search result pages. The result pages would only include posts that matches the terms of your search.

Any post that has the term you’re searching for in its title or body, WordPress will display those posts on its result pages.