Create a WordPress Search Form with Keyword & Taxonomy Support
Want more relevant search results on your WordPress site? Here’s how to add a powerful custom search form using a shortcode, allowing users to enter a keyword and filter by custom taxonomy — all with help from pre_get_posts
.
1. Shortcode to Display the Search Form
Use the following function in your theme/plugin to create a reusable shortcode:
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');
2. Filter the Query with pre_get_posts
Update your query dynamically when someone uses the form:
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');
3. Apply Styling (Optional)
.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; }
4. Add the Shortcode to Pages
Simply insert:
[custom_search_form]
Useful Developer Links