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.
Opens WPIDE on
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
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.