Using WordPress ‘get_search_template()’ PHP function

The get_search_template() WordPress PHP function retrieves the path of the search template in the current or parent theme.

Usage

$path = get_search_template();

Parameters

  • None

More information

See WordPress Developer Resources: get_search_template

Examples

Load search template in a custom search page

In this example, we load the search template in a custom search page.

$path = get_search_template();
load_template($path);

Check if the search template exists

In this example, we check if the search template exists before loading it.

$path = get_search_template();
if ($path) {
    load_template($path);
}

Modify the search template path

In this example, we modify the search template path using the search_template filter.

function my_custom_search_template($template) {
    return get_stylesheet_directory() . '/my-search.php';
}
add_filter('search_template', 'my_custom_search_template');

Display search results count in the search template

In this example, we display the search results count in the search template.

$search_template = get_search_template();
global $wp_query;
$search_results_count = $wp_query->found_posts;
echo "Found {$search_results_count} search results.";

Create a custom search results page with a plugin

In this example, we create a custom search results page using a plugin.

function custom_search_results() {
    if (is_search()) {
        $path = get_search_template();
        if ($path) {
            remove_filter('template_include', 'custom_search_results');
            load_template($path);
            add_filter('template_include', 'custom_search_results');
        }
    }
}
add_filter('template_include', 'custom_search_results');