Using WordPress ‘get_search_link()’ PHP function

The get_search_link() WordPress PHP function retrieves the permalink for a search.

Usage

get_search_link( $query );

Custom example:

$search_link = get_search_link( 'WordPress' );
echo $search_link; // Output: https://yourwebsite.com/?s=WordPress

Parameters

  • $query (string) Optional: The query string to use. If empty, the current query is used. Default: ''.

More information

See WordPress Developer Resources: get_search_link()

Examples

This example shows how to display the search link for the keyword “themes”.

$search_link = get_search_link( 'themes' );
echo 'Search for themes: ' . $search_link;

This example shows how to display the search link for a user-provided query.

$user_query = $_GET['search'];
$search_link = get_search_link( $user_query );
echo 'Search for ' . $user_query . ': ' . $search_link;

Redirect to the search results page

This example shows how to redirect the user to the search results page based on their input.

$user_query = $_POST['search'];
$search_link = get_search_link( $user_query );
header( 'Location: ' . $search_link );

This example shows how to display a search link with a custom URL structure using the “search_rewrite_rules” filter.

function custom_search_rewrite_rules() {
    return array( 'search/(.+)/?' => 'index.php?s=$matches[1]' );
}
add_filter( 'search_rewrite_rules', 'custom_search_rewrite_rules' );

$search_link = get_search_link( 'plugins' );
echo 'Search for plugins: ' . $search_link;

This example shows how to create a search form with the search link as the action.

<form action="<?php echo get_search_link(); ?>" method="get">
    <input type="text" name="s" placeholder="Search...">
    <button type="submit">Search</button>
</form>