Using WordPress ‘install_theme_search_form()’ PHP function

The install_theme_search_form() WordPress PHP function displays a search form for searching themes in the WordPress theme directory.

Usage

install_theme_search_form( $type_selector );

Example:

install_theme_search_form( true );

Parameters

  • $type_selector (bool) (Optional) – Whether to display the theme type selector (default: true).

More information

See WordPress Developer Resources: install_theme_search_form

Examples

Display theme search form with type selector

This code displays the theme search form with the type selector (default behavior).

install_theme_search_form();

Display theme search form without type selector

This code displays the theme search form without the type selector.

install_theme_search_form( false );

Add the theme search form to a custom page

This code snippet adds the theme search form to a custom page with a slug ‘theme-search’.

add_shortcode( 'theme_search_form', 'display_theme_search_form' );

function display_theme_search_form() {
    ob_start();
    install_theme_search_form();
    return ob_get_clean();
}

Then, you can add the [theme_search_form] shortcode to the content of your ‘theme-search’ page.

Display theme search form in a widget

This code creates a custom widget that displays the theme search form.

class Theme_Search_Form_Widget extends WP_Widget {
    public function __construct() {
        parent::__construct(
            'theme_search_form_widget',
            'Theme Search Form',
            array( 'description' => 'A widget for displaying the theme search form' )
        );
    }

    public function widget( $args, $instance ) {
        echo $args['before_widget'];
        install_theme_search_form();
        echo $args['after_widget'];
    }
}

function register_theme_search_form_widget() {
    register_widget( 'Theme_Search_Form_Widget' );
}
add_action( 'widgets_init', 'register_theme_search_form_widget' );

Display theme search form in a menu

This code adds the theme search form to a navigation menu.

function add_theme_search_form_to_nav_menu( $items, $args ) {
    if ( $args->theme_location == 'primary' ) {
        $items .= '<li class="menu-item theme-search-form">';
        $items .= install_theme_search_form();
        $items .= '</li>';
    }
    return $items;
}
add_filter( 'wp_nav_menu_items', 'add_theme_search_form_to_nav_menu', 10, 2 );

Replace ‘primary’ with your theme’s specific menu location.