search
HomeCMS TutorialWordPressHow to Add an Advanced Search to Your WordPress Site

How to Add an Advanced Search to Your WordPress Site

How to Add an Advanced Search to Your WordPress Site

Key Takeaways

  • WordPress search forms can be enhanced beyond the basic querystring parameter ‘s’ by using other parameters deep within the WordPress core, allowing for more focused search results.
  • Search results can be refined by category or tag by passing their respective slugs to the ‘category_name’ or ‘tag’ parameters, respectively. This can be done without the need for plugins.
  • Advanced searches can be further refined by multiple values using PHP array parameters, which can be intercepted and set in the WordPress theme’s functions.php file. This allows users to choose multiple tags for a more focused search.
The majority of WordPress search forms set a single querystring parameter named ‘s’:
<span><span><span><form> method<span>="get"</span> action<span>="<?php bloginfo('url'); ?>"</span>></form></span>
</span><span><span><span><fieldset>></fieldset></span>
</span><span><span><span><input> type<span>="text"</span> name<span>="s"</span> value<span>=""</span> placeholder<span>="search…"</span> maxlength<span>="50"</span> required<span>="required"</span> /></span>
</span><span><span><span><button> type<span>="submit"</span>></button></span>Search<span><span></span>></span>
</span><span><span><span></span>></span>
</span><span><span><span></span>></span></span></span></span></span></span>
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.
<span><span><span><form> method<span>="get"</span> action<span>="<?php bloginfo('url'); ?>"</span>></form></span>
</span><span><span><span><fieldset>></fieldset></span>
</span><span><span><span><input> type<span>="text"</span> name<span>="s"</span> value<span>=""</span> placeholder<span>="search…"</span> maxlength<span>="50"</span> required<span>="required"</span> /></span>
</span><span><span><span><button> type<span>="submit"</span>></button></span>Search<span><span></span>></span>
</span><span><span><span></span>></span>
</span><span><span><span></span>></span></span></span></span></span></span>
Our search form can allow the user to refine their search to specific categories:
http://yoursite.com/?s=search+term&category_name=kittens
If you’d rather list all categories, add the following code between the tags:
<span><span><span><form> method<span>="get"</span> action<span>="<?php bloginfo('url'); ?>"</span>></form></span>
</span><span><span><span><fieldset>></fieldset></span>
</span><span><span><span><input> type<span>="text"</span> name<span>="s"</span> value<span>=""</span> placeholder<span>="search…"</span> maxlength<span>="50"</span> required<span>="required"</span> /></span>
</span><span><span><span><select> name<span>="category_name"</span>></select></span>
</span><span><span><span><option> value<span>=""</span>></option></span>all categories<span><span></span>></span>
</span><span><span><span><option> value<span>="kittens"</span>></option></span>cute kittens<span><span></span>></span>
</span><span><span><span><option> value<span>="puppies"</span>></option></span>adorable puppies<span><span></span>></span>
</span><span><span><span></span>></span>
</span><span><span><span><button> type<span>="submit"</span>></button></span>Search<span><span></span>></span>
</span><span><span><span></span>></span>
</span><span><span><span></span>></span></span></span></span></span></span></span></span></span></span>

Refine Search by Tag

Search results can be limited to a tag by passing its slug to the tag parameter, e.g.
<span><span><?php </span></span><span><span>// generate list of categories
</span></span><span><span>$categories = get_categories();
</span></span><span><span>foreach ($categories as $category) {
</span></span><span>	<span>echo '<option value="', $category->slug, '">', $category->name, "</option>\n";
</span></span><span><span>}
</span></span><span><span>?></span></span></span>
Your search from could therefore limit results to certain tags, e.g.
http://yoursite.com/?s=search+term&tag=cockroach
Similarly, you can generate a list of all tags for the select field:
<span><span><span><form> method<span>="get"</span> action<span>="<?php bloginfo('url'); ?>"</span>></form></span>
</span><span><span><span><fieldset>></fieldset></span>
</span><span><span><span><input> type<span>="text"</span> name<span>="s"</span> value<span>=""</span> placeholder<span>="search…"</span> maxlength<span>="50"</span> required<span>="required"</span> /></span>
</span><span><span><span><select> name<span>="tag"</span>></select></span>
</span><span><span><span><option> value<span>=""</span>></option></span>any tag<span><span></span>></span>
</span><span><span><span><option> value<span>="cockroach"</span>></option></span>cockroaches<span><span></span>></span>
</span><span><span><span><option> value<span>="snake"</span>></option></span>snakes<span><span></span>></span>
</span><span><span><span></span>></span>
</span><span><span><span><button> type<span>="submit"</span>></button></span>Search<span><span></span>></span>
</span><span><span><span></span>></span>
</span><span><span><span></span>></span></span></span></span></span></span></span></span></span></span>
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:
<span><span><?php </span></span><span><span>// generate list of tags
</span></span><span><span>$tags = get_tags();
</span></span><span><span>foreach ($tags as $tag) {
</span></span><span>	<span>echo '<option value="', $tag->slug, '">', $tag->name, "</option>\n";
</span></span><span><span>}
</span></span><span><span>?></span></span></span>
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.
<span><span><span><form> method<span>="get"</span> action<span>="<span><?php bloginfo('url'); ?></span>"</span>></form></span>
</span><span><span><span><fieldset>></fieldset></span>
</span><span><span><span><input> type<span>="text"</span> name<span>="s"</span> value<span>=""</span> placeholder<span>="search…"</span> maxlength<span>="50"</span> required<span>="required"</span> /></span>
</span><span><span><span><p>></p></span>Refine search to posts containing chosen tags:<span><span></span>></span>
</span><span><span><?php </span></span><span><span>// generate list of tags
</span></span><span><span>$tags = get_tags();
</span></span><span><span>foreach ($tags as $tag) {
</span></span><span>	<span>echo 
</span></span><span>		<span>'<label>',
</label></span></span><span>		<span>'<input type="checkbox" name="taglist[]" value="',  $tag->slug, '"> ',
</span></span><span>		<span>$tag->name,
</span></span><span>		<span>"\n";
</span></span><span><span>}
</span></span><span><span>?></span>
</span><span><span><span><button> type<span>="submit"</span>></button></span>Search<span><span></span>></span>
</span><span><span><span></span>></span>
</span><span><span><span></span>></span></span></span></span></span></span></span></span>
Finally, we use the pre_get_posts action hook to run our advanced_search_query function before a query is executed:
<span>// advanced search functionality
</span><span>function advanced_search_query($query) {
</span>
	<span>if($query->is_search()) {
</span>		
		<span>// tag search
</span>		<span>if (isset($_GET['taglist']) && is_array($_GET['taglist'])) {
</span>			<span>$query->set('tag_slug__and', $_GET['taglist']);
</span>		<span>}
</span>	
		<span>return $query;
</span>	<span>}
</span>
<span>}</span>
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.

The above is the detailed content of How to Add an Advanced Search to Your WordPress Site. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The 5 Best IDEs for WordPress Development (And Why)The 5 Best IDEs for WordPress Development (And Why)Mar 03, 2025 am 10:53 AM

Choosing the Right Integrated Development Environment (IDE) for WordPress Development For ten years, I've explored numerous Integrated Development Environments (IDEs) for WordPress development. The sheer variety—from free to commercial, basic to fea

Create WordPress Plugins With OOP TechniquesCreate WordPress Plugins With OOP TechniquesMar 06, 2025 am 10:30 AM

This tutorial demonstrates building a WordPress plugin using object-oriented programming (OOP) principles, leveraging the Dribbble API. Let's refine the text for clarity and conciseness while preserving the original meaning and structure. Object-Ori

How to Pass PHP Data and Strings to JavaScript in WordPressHow to Pass PHP Data and Strings to JavaScript in WordPressMar 07, 2025 am 09:28 AM

Best Practices for Passing PHP Data to JavaScript: A Comparison of wp_localize_script and wp_add_inline_script Storing data within static strings in your PHP files is a recommended practice. If this data is needed in your JavaScript code, incorporat

How to Embed and Protect PDF Files With a WordPress PluginHow to Embed and Protect PDF Files With a WordPress PluginMar 09, 2025 am 11:08 AM

This guide demonstrates how to embed and protect PDF files within WordPress posts and pages using a WordPress PDF plugin. PDFs offer a user-friendly, universally accessible format for various content, from catalogs to presentations. This method ens

Is WordPress easy for beginners?Is WordPress easy for beginners?Apr 03, 2025 am 12:02 AM

WordPress is easy for beginners to get started. 1. After logging into the background, the user interface is intuitive and the simple dashboard provides all the necessary function links. 2. Basic operations include creating and editing content. The WYSIWYG editor simplifies content creation. 3. Beginners can expand website functions through plug-ins and themes, and the learning curve exists but can be mastered through practice.

Why would anyone use WordPress?Why would anyone use WordPress?Apr 02, 2025 pm 02:57 PM

People choose to use WordPress because of its power and flexibility. 1) WordPress is an open source CMS with strong ease of use and scalability, suitable for various website needs. 2) It has rich themes and plugins, a huge ecosystem and strong community support. 3) The working principle of WordPress is based on themes, plug-ins and core functions, and uses PHP and MySQL to process data, and supports performance optimization.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools