Family Encyclopedia >> Electronics

How to Easily Add a WordPress Search Form to Posts and Pages Using a Shortcode

One of our longtime readers recently asked for a straightforward way to embed a WordPress search form directly into post or page content via a shortcode. As experienced WordPress developers, we're happy to share this simple solution that we've used across numerous sites.

To implement it, open your active theme's functions.php file or a site-specific plugin, and add this code:

add_shortcode( 'wpbsearch', 'get_search_form' );

Now, drop [wpbsearch] into any post or page editor. It will render the default WordPress search form seamlessly.

For a custom search form, create your own function. Here's a reliable example with a Spanish label ("Buscar:" for "Search:"):

function wpbsearchform( $form ) {
    $form = '<form role="search" method="get" class="search-form" action="' . home_url( '/' ) . '">
        <label>' . __( 'Buscar:', 'textdomain' ) . '</label>
        <input type="search" class="search-field" placeholder="' . __( 'Buscar:', 'textdomain' ) . '" value="' . get_search_query() . '" name="s" />
        <input type="submit" class="search-submit" value="' . __( 'Buscar', 'textdomain' ) . '" />
    </form>';
    return $form;
}
add_shortcode( 'wpbsearch', 'wpbsearchform' );

This method ensures compatibility and customization flexibility. We've tested it extensively to boost site navigation effectively.