# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Search](https://wpide.com/library/category/search/)
- Tags: search, categories, forms
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/search-form-category-dropdown/

## Code

```php
// 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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Category Dropdown in the Search Form" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
