I have a typical WordPress site, with a typical Search page template set up which uses the typical GET format
<form id="searchform" action="http://example.com" method="get">
<input id="s" type="text" name="s" placeholder="Search Again">
</form>
For users’ convenience, I’d like to have the following url redirect to the search page template:
http://example.com/search/
But since there is no /search page or post it doesn’t. It throws a 404.
So what I want is for…
http://example.com/search/
…to behave like:
http://example.com/?s=
How do I do this?
1
You can use template_redirect. Here a simple redirection function.
add_action( 'template_redirect', 'se219663_template_redirect' );
function se219663_template_redirect()
{
global $wp_rewrite;
if ( is_search() && ! empty ( $_GET['s'] ) )
{
$s = sanitize_text_field( $_GET['s'] ); // or get_query_var( 's' )
$location = "https://wordpress.stackexchange.com/";
$location .= trailingslashit( $wp_rewrite->search_base );
$location .= user_trailingslashit( urlencode( $s ) );
$location = home_url( $location );
wp_safe_redirect( $location, 301 );
exit;
}
}
Rule without search query, like this ( don’t forget go to Permalink Settings to flush the rules ):
add_filter( 'search_rewrite_rules', 'se219663_search_rewrite_rules', 10, 1 );
function se219663_search_rewrite_rules( $rewrite )
{
global $wp_rewrite;
$rules = array(
$wp_rewrite->search_base . '/?$' => 'index.php?s=",
);
$rewrite = $rewrite + $rules;
return $rewrite;
}
and redirect with empty search query, just use isset, modified from the code above.
add_action( "template_redirect', 'se219663_template_redirect' );
function se219663_template_redirect()
{
global $wp_rewrite;
if ( is_search() && isset ( $_GET['s'] ) )
{
$s = sanitize_text_field( $_GET['s'] ); // or get_query_var( 's' )
$location = "https://wordpress.stackexchange.com/";
$location .= trailingslashit( $wp_rewrite->search_base );
$location .= ( ! empty ( $s ) ) ? user_trailingslashit( urlencode( $s ) ) : urlencode( $s );
$location = home_url( $location );
wp_safe_redirect( $location, 301 );
exit;
}
}