Let’s say you have a WordPress site (WP is used here more as a CMS rather than a blogging platform) where all content is created using the Pages as opposed to the Posts. However, the Posts (blog functionality) are also used, but rather for notifications, news, etc.
This is one of the cases where you might need to exclude all Posts from the site search.
So how would we do that?
There is definitely more ways on how to exclude Posts or Pages from WordPress search results, but this one is particularly simple with the use of the get_post_type() function.
In the theme’s search.php file, after the start of the loop:
<?php while (have_posts()) : the_post(); ?>
add:
<?php if (get_post_type() == 'post') continue; ?>
this would obviously be different for each theme, but the complete search.php could look like this:
<?php get_header(); ?> <div id="content" class="narrowcolumn" role="main"> <?php if (have_posts()) : ?> <h2 class="pagetitle">Search Results</h2> <div class="navigation"> <div class="alignleft"><?php next_posts_link('« Older Entries') ?></div> <div class="alignright"><?php previous_posts_link('Newer Entries »') ?></div> </div> <?php while (have_posts()) : the_post(); ?> <?php if (get_post_type() == 'post') continue; ?> <div <?php post_class() ?>> <h3 id="post-<?php the_ID(); ?>"> <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"> <?php the_title(); ?> </a> </h3> <small><?php the_time('l, F jS, Y') ?></small> <p class="postmetadata"> <?php the_tags('Tags: ', ', ', '<br />'); ?> Posted in <?php the_category(', ') ?> | <?php edit_post_link('Edit', '', ' | '); ?> <?php comments_popup_link('No Comments »', '1 Comment »', '% Comments »'); ?> </p> </div> <?php endwhile; ?> <div class="navigation"> <div class="alignleft"><?php next_posts_link('« Older Entries') ?></div> <div class="alignright"><?php previous_posts_link('Newer Entries »') ?></div> </div> <?php else : ?> <h2 class="center">No posts found. Try a different search?</h2> <?php get_search_form(); ?> <?php endif; ?> </div> <?php get_sidebar(); ?> <?php get_footer(); ?>
possibly you might want to exclude few of the Pages as well by listing the page IDs in an array:
<?php if (get_post_type() == 'post') continue; ?> <?php if( in_array($post->ID, array('410','412','575','8','156') ) ) continue; ?>
That’s it. Hope this helps someone…
Tags: search, wordpress, wordpress exclude from search, wordpress exclude search results, wp