Adding multiple hidden fields to filter wordpress search

Posted on 4th March, 2017 Leave a Comment

To add multiple fields you’ll first need to create a small funciton in your functions.php

 

/**
 * Custom Search Queries 
 * Allows the use of multiple hidden filters on search.php
 *************************************************************/
function SearchFilter($query) {
$post_type = $_GET['post_type'];
if (!$post_type) {
    $post_type = 'any';
}
if ($query->is_search) {
    $query->set('post_type', $post_type);
};
return $query;
} 

Then in your searchform.php you can add hidden fields like this.

<form method="get" action="<?php bloginfo('url'); ?>/">
	<label for="s">Search the site: </label>
	<input type="text" id="s" name="s" value="<?php the_search_query(); ?>">

	<!-- Search only these custom post types -->
			<input type="hidden" name="post_type[]" value="page">
			<input type="hidden" name="post_type[]" value="services">
			<input type="hidden" name="post_type[]" value="solutions">
			<input type="hidden" name="post_type[]" value="resources">
			<input type="hidden" name="post_type[]" value="technology">
			<input type="hidden" name="post_type[]" value="about">
	<input type="submit" value="Search">
</form>

If you want to do this with any other filter, for example categories. Repeat the above and replace post_type with cat.

Leave a Comment

To preserve code added to a comment you can wrap your code in short tags
by using [square brackets]:

  1. PHP use - [php] <?php code here ?> [/php]
  2. CSS use - [css] #code-here {} [/css]
  3. HTML use - [html] <div> code here </div> [/html]
  4. JS use - [js] $(".codeHere") [/js]