How to Create a WordPress Search Form with Keyword and Custom Taxonomy Filters
If you’re looking to enhance your WordPress search functionality, this guide shows you how to build a custom search form that filters by both keyword and custom taxonomy using a shortcode and the pre_get_posts hook.
Step 1: Create the Custom Search Form with Shortcode
This shortcode renders a form with keyword input and a dropdown to select custom taxonomy terms.
function custom_search_form_shortcode() {
ob_start();
?>
<form role="search" method="get" class="search-form" action="<?php echo esc_url(home_url('/')); ?>">
<div class="search-form-row">
<label for="search-keyword">Search Keyword:</label>
<input type="text" id="search-keyword" name="s" placeholder="Enter your keyword..." value="<?php echo get_search_query(); ?>" />
</div>
<div class="search-form-row">
<label for="search-taxonomy">Filter by Custom Taxonomy:</label>
<?php
$taxonomy = 'your_custom_taxonomy'; // Change this to your taxonomy
$terms = get_terms($taxonomy, array('hide_empty' => false));
?>
<select name="custom_taxonomy" id="search-taxonomy">
<option value="">All <?php echo $taxonomy; ?></option>
<?php foreach ($terms as $term) : ?>
<option value="<?php echo esc_attr($term->slug); ?>" <?php selected($term->slug, get_query_var('custom_taxonomy')); ?>>
<?php echo esc_html($term->name); ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="search-form-row">
<button type="submit" class="search-submit">Search</button>
</div>
</form>
<?php
return ob_get_clean();
}
add_shortcode('custom_search_form', 'custom_search_form_shortcode');
Step 2: Modify the Main Query with pre_get_posts
Use pre_get_posts to make WordPress understand the new filter and keyword query:
function custom_search_pre_get_posts($query) {
if (is_admin() || !$query->is_main_query()) return;
if ($query->is_search()) {
if (!empty($_GET['s'])) {
$query->set('s', sanitize_text_field($_GET['s']));
}
if (!empty($_GET['custom_taxonomy'])) {
$query->set('tax_query', array(
array(
'taxonomy' => 'your_custom_taxonomy',
'field' => 'slug',
'terms' => sanitize_text_field($_GET['custom_taxonomy']),
),
));
}
}
}
add_action('pre_get_posts', 'custom_search_pre_get_posts');
Step 3: Add Custom CSS to Style the Form
.search-form {
display: flex;
flex-wrap: wrap;
margin-top: 20px;
}
.search-form-row {
margin-bottom: 12px;
}
.search-form label {
font-weight: bold;
display: block;
margin-bottom: 5px;
}
.search-form input[type="text"],
.search-form select {
padding: 8px;
width: 250px;
}
.search-form .search-submit {
padding: 8px 20px;
background-color: #0073aa;
color: #fff;
border: none;
cursor: pointer;
}
.search-form .search-submit:hover {
background-color: #005a88;
}
Step 4: Display the Search Form Using the Shortcode
To show the form anywhere (pages, posts, widgets), use the shortcode:
[custom_search_form]
⚠️ Remember to replace 'your_custom_taxonomy' with your actual taxonomy name in both form and query hook.
Additional Resources
