Category Dropdown in the Search Form
Adds a category dropdown to the site search form and the Search block, so visitors can search all content or only one category.
Opens WPIDE on
Code
// Text of the first option, which searches everything.
$wpide_search_cat_all = 'All categories';
$wpide_search_cat_select = function () use ( $wpide_search_cat_all ) {
static $html = null;
if ( null === $html ) {
$id = wp_unique_id( 'wpide-search-cat-' );
$html = '<label class="screen-reader-text" for="' . esc_attr( $id ) . '">Category</label>' . wp_dropdown_categories( array(
'show_option_all' => $wpide_search_cat_all,
'name' => 'cat',
'id' => $id,
'class' => 'wpide-search-cat',
'selected' => absint( get_query_var( 'cat' ) ),
'hierarchical' => true,
'hide_empty' => true,
'echo' => false,
) );
}
return $html;
};
$wpide_search_cat_insert = function ( $form ) use ( $wpide_search_cat_select ) {
if ( false !== strpos( $form, 'wpide-search-cat' ) ) {
return $form;
}
// Before the search button, or before the end of the form when there is no button.
$count = 0;
$form = preg_replace( '#(<button|<input[^>]+type=["\']submit)#i', $wpide_search_cat_select() . '$1', $form, 1, $count );
return $count ? $form : str_replace( '</form>', $wpide_search_cat_select() . '</form>', $form );
};
add_filter( 'get_search_form', $wpide_search_cat_insert );
add_filter( 'render_block_core/search', $wpide_search_cat_insert );
add_action( 'wp_head', function () {
echo '<style>.wpide-search-cat{max-width:100%;margin:0 .25em}.wp-block-search__inside-wrapper .wpide-search-cat{border:0;background:transparent}</style>';
} );
Notes
Do not combine with the Search Within the Current Category snippet; both use the same field.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.