Useful Resources for Web Designers and Developers

Advertise

here through BuySellAds

How to Create an Advanced Search Form for WordPress

October 9, 2012 on General, Tutorials

So you want to learn how they do those pretty slick WordPress search forms. The ones that have drop downs of categories, filtering through your posts as soon as you press submit. These are most often used in advanced themes such as eCommerce, job posting and real estate themes. These search forms are a real nice addition to your site – making it more usable and user friendly.

I’m going to assume that you are pretty well versed in WordPress theme development. If you’re not, here is a pretty good starter series from Udemy on WordPress site development. I’m also going to assume that you know what custom post types are, and know how to create them. I’m also assuming that you know what taxonomies are. These two things are crucial to our form. Without them, we don’t have much to work with.

Below is a screenshot of how our form will look. The demo link above links to our Free Real Estate WordPress Theme, which has the form right in the home page. In fact, this tutorial is based on how that functionality is achieved.

form How to Create an Advanced Search Form for Wordpress

So ready to get started? Let’s roll up our sleeves and begin.

Build the Form

As I’ve mentioned, we are working with custom post types and taxonomies. For this tutorial, we are working with a post type named “Listings”. We have also attached several taxonomies to this post type – named: “Type“, “Rooms“, “Area” and “Price“.

As you can imagine, a Real Estate website will have visitors who wish to search through your listings that match only the ones that are “Single Family“, “3 Bedrooms“, in “Chicago, IL” and “under $100,000“.

So you see how this can be real handy.

custom post type How to Create an Advanced Search Form for Wordpress

So first we write a function that will return html. Let’s use WordPress function get_terms() to populate our select tags. In your functions.php, add the code below:

1
2
3
4
5
6
7
8
9
10
function buildSelect($tax){	
	$terms = get_terms($tax);
	$x = '<select name="'. $tax .'">';
	$x .= '<option value="">Select '. ucfirst($tax) .'</option>';
	foreach ($terms as $term) {
	   $x .= '<option value="' . $term->slug . '">' . $term->name . '</option>';	
	}
	$x .= '</select>';
	return $x;
}

The above function will run get_terms() on the Taxonomy passed, and will return several option tags with the term slug and name in it. So in your template (where you want your form to appear), create a form and use the function we just created.

1
2
3
4
5
6
7
8
<form  method="post" action="<?php bloginfo('url');?>/listing-search-results/"> 
<?php  $taxonomies = get_object_taxonomies('listings');
    foreach($taxonomies as $tax){
        echo buildSelect($tax);
    }
?>
<input type="submit"/>	
</form>

Test your form and see your drop down lists populate with the right Taxonomy terms. If not, make sure you’ve added the right terms for each Taxonomy in your blog.

Also note the form action “/listing-search-results/“. This is a page we have yet to build – one that will handle the form processing. We will cover that in the next section.

The Processing

You will need to create a page template – name it “Custom Search Results“. For information on how to create page templates for your theme, click here. Now, on this page – start with the code below:

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php  
$list = array();
$item = array();  
foreach($_POST as $key => $value){
	if($value != ''){
		$item['taxonomy'] = htmlspecialchars($key);
		$item['terms'] = htmlspecialchars($value);
		$item['field'] = 'slug';
		$list[] = $item;
	}		
}  
$cleanArray = array_merge(array('relation' => 'AND'), $list);
?>

The code above creates two empty arrays. $item is filled up with each $_POST key and value, and added to the $list array. $cleanArray is a merge with “relation” key with value “AND” to our existing $list array.

So once a user selects items from our drop down lists and submits the form, it should supply the values needed for our arrays. Do a print_r() on the $cleanArray and the output should be similar to below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
Array
(
    [relation] => AND
    [0] => Array
        (
            [taxonomy] => type
            [terms] => condo
            [field] => slug
        )
 
    [1] => Array
        (
            [taxonomy] => rooms
            [terms] => 2-3-bedrooms
            [field] => slug
        )
 
    [2] => Array
        (
            [taxonomy] => area
            [terms] => la-crescenta
            [field] => slug
        )
 
    [3] => Array
        (
            [taxonomy] => price
            [terms] => 300k-400k
            [field] => slug
        )
 
)

Now we have enough to query our database with. Add the lines of code below:

1
2
3
4
5
6
$args['post_type'] = 'listings';
$args['showposts'] = 9;
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args['paged'] = $paged;  
$args['tax_query'] = $cleanArray; 
$the_query = new WP_Query( $args );

The above code sets up a few more variables. These are the needed arguments we need to pass into the WP_Query object – which does all the querying.

As you see, we’re querying post_type “listings” and returning only 9 items. “paged” is needed for pagination to work, and the main argument “tax_query” – tells the object to query taxonomies. Also note that inside WP_Query is plenty of data sanitation – so data is clean once passed.

The Output

So once data is sent to the WP_Query object, all we need to do is loop through it and display the output. Our WP_Query object (now $the_query) has all the methods to produce the needed results. Add the code below:

1
2
3
4
5
6
7
8
9
10
11
<?php echo ($the_query->found_posts > 0) ? '<h3 class="foundPosts">' . $the_query->found_posts. ' listings found</h3>' : '<h3 class="foundPosts">We found no results</h3>';?>
	<?php while ( $the_query->have_posts() ) : $the_query->the_post();?>
 
	//add our code here i.e. the_title();
 
	<?php endwhile; wp_reset_postdata();?>		 
 
<div class="row page-navigation"> 
	 <?php next_posts_link('&laquo; Older Entries', $the_query->max_num_pages) ?> 
	 <?php previous_posts_link('Newer Entries &raquo;') ?> 
</div>

The code above behaves like a normal WordPress loop. So insert regular template tags inside the “while” loop and your output should render. Notice the use of post navigation (next_posts_link) in the bottom of the code? It should behave like normal posts pagination in WordPress.

results How to Create an Advanced Search Form for Wordpress

Our results page with formatting etc.

Conclusion

There you have it. An advanced search form that will filter through your custom post types. You can display this search form in any part of your website – ideally in your sidebar or header area. I especially like this treatment because it highlights your custom post type all the more. Making it really stand out from your regular blog posts.

Useful Resources:

Make sure you go through these links to better understand what the code above does.

  1. WordPress Codex – WP_Query
  2. Advanced Taxonomy Queries – Ottopress
  3. Advanced Search Form Filters – WPAnswers

If you haven’t already – download our “Realty WordPress Theme” – which has the code above in place. See how it works as you install it in your next Real Estate WordPress site. Also read this post on How this theme can compete with other Premium Real Estate Themes. If you have suggestions, questions or improvements to the code, please feel free to leave a comment below.

Don’t forget to check out Udemy’s WordPress site building series.

  • Camila

    Hi, I need some help. I need to insert a code for each property, and I managed to do this using get_the_ID() but I can’t make the code wordks on the search of wordpress… The cliente search for the code and the property don’t appear in searches …
    You can help me?
    sorry for my english..

    • http://fearlessflyer.com Michael Soriano

      Hi Camila,

      this search form will only target your custom post type.

  • http://www.cityflavourmagazine.com abbey

    Hi ,

    thanks for this great tutorial. please how can i have one of the taxonomy as text field rather than a dropdown.

    I have 2 taxonomy(one as cats and one as tags)

    My tags is for postcode which i want to be a text field.

    my categories is dropdown which is fine.

    please how can i achieve this.

    thanks a lot.

  • DI BERÇUS Infantil

    Please How do I change file names Type, Rooms, Living and Price,? For my language is Portuguese.

    thank you