Exclude pages in Wordpress 2.8 search

No comments

In Wordpress, it's always been easy to throw a search box into your blog's theme that searches across your blog:

<form id="searchform" method="get" action="<?php bloginfo('home'); ?>">
<input type="text" name="s" id="s" size="15" />
<input type="submit" value="<?php _e('Search'); ?>" />
</form> 

It used to be the case that the search function would harvest all of the information--tags, categories, content--of posts, but only of posts.  In other words, pages were excludable from the search.  However, as more users take on Wordpress for more projects, pages have begun to get used in more ways, an so the fine people at Wordpress went ahead and included pages in the site search functionality.  So in Wordpress 2.8, if you conduct a search, you get page entries too.

There are some good plugins out there to limit searching, but a generally easy and foolproof way to manipulate search in Wordpress 2.8 is to do this.

Create a search results template in your theme by creating a file called search.php.

In search.php, you'd generally have something like this:

<?php if (have_posts()) : ?>

<h2>Search Results</h2>
<?php while (have_posts()) : the_post(); ?>
<?php /* your post formatting code in here */ ?>
<?php endwhile; ?>
<?php else : ?>
<h2>No posts found. Try a different search?</h2>
<?php endif; ?>

To ignore pages, under the while loop, add this line:

<?php if (is_type_page()) continue; ?>

So then your while loop looks like this:

<?php while (have_posts()) : the_post(); ?> 
<?php if (is_type_page()) continue; ?>
<?php /* your post formatting code in here */ ?>
<?php endwhile; ?>

Then in the functions.php file, make sure this function is there:

function is_type_page() {   
  global $post; 
  return ($post->post_type == 'page');
}

A function similar to this comes in many of the default themes but not all of them, so if you're writing your own theme, even if you're basing it off a default one, you may need to throw this in there. (This function made sexier courtesy of cha0s, fellow programming-genius)

You can filter a lot about the search with this function.  The Wordpress codex has a good list of returned variables you can use to build an exclusive search.

Syndicate

Syndicate content
Powered by Drupal, an open source content management system