Customised search scope in WordPress

Sometimes in a WordPress site you might want to have the option to search within different types of content. For example, if one category contains blog posts and another one contains white papers, you might want to allow people to restrict their search query to blog posts only. Here is a slightly hacky way to achieve this.

Create a specific template for displaying search results – search.php. Then, by placing an extra field in your search forms, you can check for this value within search.php and display or hide certain categories depending on what you detect.

So for example on your homepage you might have a search form with a field like this:

<label>Restrict search to blog: <input name="scope" type="radio" value="blog" /></label>

Then within search.php you would pick up that value like this:

<?php $scope = $_GET['scope']; ?>

And then use that to skip certain categories within the loop:

<?php while (have_posts()) : the_post(); ?>
//Skip this result if it's out of scope:
<?php if($scope == 'blog' && !in_category(1)) continue; ?>
....

Of course you can make this more complex by setting up multiple scopes and including more categories in each.

5 Comments

  1. Hi there, do you have a working example of the above? sounds good.

  2. Hi Bjarni

    I have a working example but currently on a development server only, for a client project. Guess I could make a public working version sometime when I get a moment, if you think that’s useful.

    Ben

  3. i would appreciate it if you do post up a working example.

    my problem is i want to be able to custom my search to ONLY certain categories, and ONLY by certain fields (Titles) or by custom fields (actors.)

    as you may guess, i’m doing a movie review site.

    any help is appreciated, thanks

  4. In that case it may be better to run a custom query on the WP database.

    I think you could still detect your various search parameters via $_GET variable. Then use those parameters to construct a custom query using $wpdb->get_results(). See http://codex.wordpress.org/Displaying_Posts_Using_a_Custom_Select_Query for more info.

    Good luck!

Leave a comment