# Search Form Shortcode With Post Type Filter

> Adds a [search_form] shortcode that places a search box anywhere and can limit results to certain post types, such as a docs-only or products-only search.

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

## Code

```php
add_shortcode( 'search_form', function ( $atts ) {
    $atts = shortcode_atts( array(
        'post_type'   => '',
        'placeholder' => 'Search...',
        'button'      => 'Search',
    ), $atts, 'search_form' );

    $id    = wp_unique_id( 'wpide-search-' );
    $types = array_filter( array_map( 'sanitize_key', explode( ',', $atts['post_type'] ) ), 'post_type_exists' );

    $html  = '<form role="search" method="get" class="search-form wpide-search-form" action="' . esc_url( home_url( '/' ) ) . '">';
    $html .= '<label class="screen-reader-text" for="' . esc_attr( $id ) . '">Search for:</label>';
    $html .= '<input type="search" id="' . esc_attr( $id ) . '" class="search-field" name="s" value="' . esc_attr( get_search_query() ) . '" placeholder="' . esc_attr( $atts['placeholder'] ) . '" />';

    foreach ( $types as $type ) {
        $html .= '<input type="hidden" name="post_type[]" value="' . esc_attr( $type ) . '" />';
    }

    return $html . ' <button type="submit" class="search-submit wp-element-button">' . esc_html( $atts['button'] ) . '</button></form>';
} );
```

## Notes

Example: [search_form post_type="docs" placeholder="Search the docs" button="Go"]. Pages cannot be targeted this way because WordPress does not allow them in query URLs.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Search Form Shortcode With Post Type Filter" 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/
