I am learning to build a fully custom WordPress theme. I have a search form
<form role="search" method="get" class="search-form" action="<?php echo home_url() ?>/">
<input type="search" placeholder="Search …" value="" id="s" name="s" required />
<button type="submit"><i class="fa fa-search"></i></button>
</form>
which renders the following HTML:
<form role="search" method="get" class="search-form" action="http://local.devsite.com/">
<input type="search" placeholder="Search …" value="" id="s" name="s" required />
<button type="submit"><i class="fa fa-search"></i></button>
</form>
In my search.php
template, I currently have the following code to check whether everything works as desired:
if( empty( $_GET['s'] ) ) {
echo 'No search';
exit;
}
$s = $_GET['s'];
echo $s;
When I run http://local.devsite.com/?s=sedan
, I get the value of $_GET['s']
printed on the search page perfectly
However, I want the URL to look like the following:
http://local.devsite.com/search/sedan
, so I added the following code in my theme's functions.php
file.
function yd_change_search_url() {
if ( is_search() && ! empty( $_GET['s'] ) ) {
wp_redirect( home_url( "/search/" ) . urlencode( get_query_var( 's' ) ) );
exit();
}
}
add_action( 'template_redirect', 'yd_change_search_url' );
After adding the code, I resaved Settings > Permalinks
. But when I run http://local.devsite.com/search/sedan
, I get No Search message on the search page.
The phrase No Search is printed when an empty $_GET['s']
is encountered according to the following code that I have added in search.php
template.
if( empty( $_GET['s'] ) ) {
echo 'No search';
exit;
}
$s = $_GET['s'];
echo $s;
What I am doing wrong? I am following this tutorial.
My ultimate goal is to build a URL with multiple query strings, i.e.
http://local.devsite.com/?s=sedan&mfg=2010&model=Mark%20X&cond=used,
which would ultimately transform after rewriting to this
http://local.mydev.com/sedan/2010/mark-x/used