WordPress – Search only posts or pages

One annoyance I have with WordPress default searching is that it searches everything and gives no context to the search results. At times you may want to search specifically for pages in a corporate site and other times in the context of a blog, search specifically for posts.

It’s simple to accomplish this by adding a hidden input field in your form tag.

<?php if(is_page()):?>
    <input type="hidden" name="post_type" value="page" />
<?php elseif(is_archive()):?>
    <input type="hidden" name="post_type" value="post" />
<?php endif;?>

You can also use radio buttons to allow your users to decide what results are returned:

<form method="get" action="<?php echo home_url();?>">
    <input type="text" name="s" />
    <label>Search Pages</label>
    <input type="radio" name="post_type" value="page" />
    <label>Search Posts</label>
    <input type="radio" name="post_type" value="post" />
    <button type="submit">Submit</button>
</form>

This works dandy. See my post on Stack Exchange about this topic.