-
I want to extend the Search option (magnifying glass in menu that opens the modal) with 2 radioboxes:
-Broad
-ExactThe code:
<form role=”search” method=”get” class=”search-form” action=”<?php echo home_url(‘/’); ?>”>
<label>
<input type=”search” class=”search-field” placeholder=”<?php echo esc_attr_x(‘Search …’, ‘placeholder’); ?>” value=”<?php echo get_search_query(); ?>” name=”s” />
</label>
<fieldset>
<legend>Search Type:</legend>
<label>
<input type=”radio” name=”search_type” value=”broad” checked> Broad
</label>
<label>
<input type=”radio” name=”search_type” value=”exact”> Exact
</label>
</fieldset>
<input type=”submit” class=”search-submit” value=”<?php echo esc_attr_x(‘Search’, ‘submit button’); ?>” />
</form>In functions.php:
function custom_search_query($query) {
if ($query->is_search() && $query->is_main_query()) {
global $wpdb;// Get the search term and search type from the query vars
$search_term = $query->query_vars[‘s’];
$search_type = isset($_GET[‘search_type’]) ? sanitize_text_field($_GET[‘search_type’]) : ‘broad’;if ($search_type === ‘exact’ && !empty($search_term)) {
// Exact search
$query->set(‘s’, ”); // Clear the default search term// Modify the SQL query to enforce exact match
add_filter(‘posts_search’, function ($search, $wp_query) use ($wpdb, $search_term) {
if ($wp_query->is_search() && !empty($search_term)) {
// Exact match on post titles and content
$search = $wpdb->prepare(” AND (({$wpdb->posts}.post_title = %s) OR ({$wpdb->posts}.post_content = %s))”, $search_term, $search_term);
}
return $search;
}, 10, 2);
} else {
// Broad search
$query->set(‘s’, $search_term);
}
}
}
add_action(‘pre_get_posts’, ‘custom_search_query’);What’s the best way to override the current search box with this functionality?
Another thing that I don’t like so much in the current search, is that the modal close if you accidentally click outside the modal. I prefer a closing icon and even a full screen modal.
-
Hi there,
What’s the best way to override the current search box with this functionality?
You can create a
block element - hook
at appearance > elements, set the element type toSearch modal
, then add your form HTML in to the block element via the Custom HTML block.Set the location to the entire site.
Let me know if this helps!
- You must be logged in to reply to this topic.