How to Add an Advanced Search to Your WordPress Site

Share this article

The majority of WordPress search forms set a single querystring parameter named ‘s’:

<form method="get" action="<?php bloginfo('url'); ?>">
<fieldset>
<input type="text" name="s" value="" placeholder="search&hellip;" maxlength="50" required="required" />
<button type="submit">Search</button>
</fieldset>
</form>
There’s nothing wrong with that and I thought it was the only option for many, many years. However, more advanced queries are possible without the aid of plugins (although plenty are available). Deep within the WordPress core, the application parses several other querystring parameters and uses them to return a more focused set of search results. There is some rudimentary documentation which lists the parameter names:
  • attachment
  • attachment_id
  • author
  • author_name
  • cat
  • category_name
  • comments_popup
  • day
  • error
  • feed
  • hour
  • m
  • minute
  • monthnum
  • name
  • p
  • page_id
  • paged
  • pagename
  • post_parent
  • post_type
  • preview
  • second
  • static
  • subpost
  • subpost_id
  • tag
  • tag_id
  • tb
  • w
  • year
I’m not convinced all these work as expected and some are a little pointless, but they match the parameters you can pass to WP_Query. We can therefore create an advanced search form using HTML with a smidgen of PHP to automate the options.

Refine Search by Category

You can limit results to a category by passing its slug to the category_name parameter, e.g.
http://yoursite.com/?s=search+term&category_name=kittens
Our search form can allow the user to refine their search to specific categories:
<form method="get" action="<?php bloginfo('url'); ?>">
<fieldset>
<input type="text" name="s" value="" placeholder="search&hellip;" maxlength="50" required="required" />
<select name="category_name">
<option value="">all categories</option>
<option value="kittens">cute kittens</option>
<option value="puppies">adorable puppies</option>
</select>
<button type="submit">Search</button>
</fieldset>
</form>
If you’d rather list all categories, add the following code between the <select> and </select>
tags:
<?php
// generate list of categories
$categories = get_categories();
foreach ($categories as $category) {
	echo '<option value="', $category->slug, '">', $category->name, "</option>\n";
}
?>

Refine Search by Tag

Search results can be limited to a tag by passing its slug to the tag parameter, e.g.
http://yoursite.com/?s=search+term&tag=cockroach
Your search from could therefore limit results to certain tags, e.g.
<form method="get" action="<?php bloginfo('url'); ?>">
<fieldset>
<input type="text" name="s" value="" placeholder="search&hellip;" maxlength="50" required="required" />
<select name="tag">
<option value="">any tag</option>
<option value="cockroach">cockroaches</option>
<option value="snake">snakes</option>
</select>
<button type="submit">Search</button>
</fieldset>
</form>
Similarly, you can generate a list of all tags for the select field:
<?php
// generate list of tags
$tags = get_tags();
foreach ($tags as $tag) {
	echo '<option value="', $tag->slug, '">', $tag->name, "</option>\n";
}
?>

Advancing Advanced Search

What if you want to refine the search by multiple values? For example, the user could choose two or more tags and resulting pages must have them all set. We cannot achieve this using URL parameters alone but let’s start by defining an HTML search form:
<form method="get" action="<?php bloginfo('url'); ?>">
<fieldset>
<input type="text" name="s" value="" placeholder="search&hellip;" maxlength="50" required="required" />
<p>Refine search to posts containing chosen tags:</p>
<?php
// generate list of tags
$tags = get_tags();
foreach ($tags as $tag) {
	echo 
		'<label>',
		'<input type="checkbox" name="taglist[]" value="',  $tag->slug, '" /> ',
		$tag->name,
		"</label>\n";
}
?>
<button type="submit">Search</button>
</fieldset>
</form>
Note that I’ve used a PHP array parameter named taglist. You can use any name other than those already reserved by WordPress (see the list above). We can now intercept a search submission in our WordPress theme’s functions.php
file. The advanced_search_query function detects whether a search is active then sets the WP_Query tag_slug__and parameter accordingly.
// advanced search functionality
function advanced_search_query($query) {

	if($query->is_search()) {
		
		// tag search
		if (isset($_GET['taglist']) && is_array($_GET['taglist'])) {
			$query->set('tag_slug__and', $_GET['taglist']);
		}
	
		return $query;
	}

}
Finally, we use the pre_get_posts action hook to run our advanced_search_query function before a query is executed:
add_action('pre_get_posts', 'advanced_search_query', 1000);
Adding advanced search facilities to WordPress is remarkably easy yet few developers realize it’s possible … perhaps because documentation and examples are a little sparse. I discovered it by accident so I hope you find this code useful in your next WordPress project.

Frequently Asked Questions on Advanced Search in WordPress

How can I customize the search results in WordPress?

Customizing search results in WordPress can be achieved by using the WP_Query class. This class allows you to define specific parameters to tailor your search results. For instance, you can set parameters to search only within post titles, exclude certain post types, or even search within custom fields. You can also use plugins like SearchWP that offer advanced search customization options.

Can I use tags to improve search results in WordPress?

Yes, tags can significantly improve search results in WordPress. By using the get_the_tags() function, you can retrieve the tags associated with a particular post. This can be used to create a more refined search experience, allowing users to search for posts with specific tags.

How can I change the search query parameter in WordPress?

The search query parameter in WordPress can be changed using the ‘query_vars’ filter. This allows you to change the default ‘s’ parameter to something more specific to your needs. For example, you can change it to ‘search_term’ to make your URLs more user-friendly.

What is WP_Query in WordPress?

WP_Query is a class in WordPress that allows you to create custom queries and loops. It provides numerous parameters that you can use to customize your queries, such as post type, category, tag, author, and more. This makes it a powerful tool for creating advanced search functionalities.

How can I exclude certain post types from search results in WordPress?

Excluding certain post types from search results can be done using the ‘pre_get_posts’ action hook in conjunction with the WP_Query class. You can set the ‘post_type’ parameter to an array of the post types you want to include in the search results, effectively excluding all others.

Can I search within custom fields in WordPress?

Yes, you can search within custom fields in WordPress using the ‘meta_query’ parameter in WP_Query. This allows you to specify a custom field key and value, and return posts that match these criteria.

How can I improve the search functionality in WordPress?

Improving search functionality in WordPress can be achieved by using plugins like SearchWP, Relevanssi, or Ajax Search Pro. These plugins offer advanced search features like partial matching, keyword stemming, and search weighting, providing a better user experience.

Can I create a search form in WordPress without a plugin?

Yes, you can create a search form in WordPress without a plugin by using the get_search_form() function. This function generates the HTML for a search form, which you can customize to suit your needs.

How can I display the search query in WordPress?

The search query can be displayed in WordPress using the get_search_query() function. This function retrieves the search query string and can be used to display the search term on your search results page.

Can I limit the number of search results in WordPress?

Yes, you can limit the number of search results in WordPress by using the ‘posts_per_page’ parameter in WP_Query. This allows you to specify the number of posts to display per page, effectively limiting the number of search results.

Craig BucklerCraig Buckler
View Author

Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.

searchWordPress
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form