Search Within the Current Category
On category pages, adds an "Only in [category]" checkbox to the search form and Search block, ticked by default, so visitors can search just that section.
Opens WPIDE on
Code
// Label of the checkbox; %s is the category name.
$wpide_search_in_cat_label = 'Only in %s';
$wpide_search_in_cat = function ( $form ) use ( $wpide_search_in_cat_label ) {
$cat_id = is_category() ? get_queried_object_id() : ( is_search() ? absint( get_query_var( 'cat' ) ) : 0 );
$cat = $cat_id ? get_category( $cat_id ) : null;
if ( ! $cat || is_wp_error( $cat ) || false !== strpos( $form, 'wpide-search-in-cat' ) ) {
return $form;
}
$box = '<label class="wpide-search-in-cat" style="display:block;flex-basis:100%;margin-top:.4em;font-size:.9em;"><input type="checkbox" name="cat" value="' . esc_attr( $cat->term_id ) . '" checked /> ' . esc_html( sprintf( $wpide_search_in_cat_label, $cat->name ) ) . '</label>';
return str_replace( '</form>', $box . '</form>', $form );
};
add_filter( 'get_search_form', $wpide_search_in_cat );
add_filter( 'render_block_core/search', $wpide_search_in_cat );
Notes
Do not combine with the Category Dropdown in the Search Form 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.