Skip to content

Instantly share code, notes, and snippets.

@timothyjensen
Created October 13, 2017 11:18
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save timothyjensen/fa4271a3b91d3466a6ce8e3d17e213de to your computer and use it in GitHub Desktop.
Modify the standard WordPress search form to perform faceted search.
<?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 &hellip;', 'placeholder' ) . '" value="' . get_search_query() . '" name="s" />
</label>
<input type="submit" class="search-submit" value="' . esc_attr_x( 'Search', 'submit button' ) . '" />
</form>';
return $form;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment