Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

Code

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 add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.