WordPress search by category

If you want to change default wordpress search capability to next level by adding facility to search posts by category.

For this we have to add category dropdown box next to the default search text box so users can search text within selected categories.

To achieve this you have to add following form code to display the text box and category dropdown.

<form id="search_form" method="get" action="<?php bloginfo('url'); ?>">
    <input type="text" name="s" id="s" size="20" />
    <?php wp_dropdown_categories('show_option_none=Select Category'); ?>
    <input type="submit" value="Search" />
</form>

it will add search form with select box of all the categories in your wordpress blog.

wp_dropdown_categories is used to display a category dropdown. by default name of the selectbox is “cat” so we don’t need to change that.

One more thing you can customize/style of that form as you want to match your website design and style.

When you press search button the result page link will look like this

https://snilesh.com/blog/?s=post-types&cat=3

when i search for post-types on my wordpress blog, and cat=3 is the category added because of that selectbox which we added.

Leave a Reply

Your email address will not be published. Required fields are marked *