If you have ever wanted to add faceted search to your WordPress site without a third party plugin, it’s actually easier than you think. You can create a search form like this without too much trouble:
With the form above, if any of the boxes are checked then WordPress will limit the search to those post types. If the boxes are left unchecked then the search scope will be site wide (default). This is the code you can add to modify your search form like I’ve done here:
<?php | |
add_filter( 'get_search_form', 'prefix_render_faceted_search_form' ); | |
/** | |
* Adds checkboxes to the search form for searching specific post types. | |
* | |
* @param string $form The search form HTML output. | |
* | |
* @return string | |
*/ | |
function prefix_render_faceted_search_form( $form ) { | |
// Associative array of post type names and labels. | |
$post_types = array( | |
'book' => 'Books', | |
'movie' => 'Movies', | |
'music' => 'Music', | |
); | |
// Build the facet checkboxes. | |
$facet_checkboxes = ''; | |
foreach ( $post_types as $name => $label ) { | |
$facet_checkboxes .= sprintf( '<label><span class="screen-reader-text">%1$s %2$s</span><input type="checkbox" name="post_type[]" value="%3$s">%2$s</label>', | |
_x( 'Search', 'label' ), | |
$label, | |
$name | |
); | |
} | |
$form = '<form role="search" method="get" class="search-form" action="' . esc_url( home_url( '/' ) ) . '"> | |
<div class="search-form__facets">' . $facet_checkboxes . '</div> | |
<label> | |
<span class="screen-reader-text">' . _x( 'Search for:', 'label' ) . '</span> | |
<input type="search" class="search-field" placeholder="' . esc_attr_x( 'Search …', 'placeholder' ) . '" value="' . get_search_query() . '" name="s" /> | |
</label> | |
<input type="submit" class="search-submit" value="' . esc_attr_x( 'Search', 'submit button' ) . '" /> | |
</form>'; | |
return $form; | |
} |
The code is basically adding three checkbox inputs, each with a name of post_type[]
and value of the post type slug/name, such as book
. This can easily be modified to create different facets as well, such as author, category, or custom taxonomy term. A full list of possibilities can be found in the “Public” section of the List of Query Vars in the WordPress Codex.
As far as I know post_type is the only public query var that accepts an array. This means that although you can create a faceted search for different categories (for example), you can only limit the search to one category at a time. So you can search within “Category 1” OR “Category 2”, but not both at the same time. For that use case it makes more sense to set up radio buttons instead of checkboxes.
Leave a Reply