0

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 &hellip;" 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 &hellip;" 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

0

I figured it out. The error was in my code in search.php template file.

My previous code was this:

if( empty( $_GET['s'] ) ) {
    echo 'No search';
    exit;
}

$s = $_GET['s'];
echo $s;

while it should be this:

if( empty( get_query_var( 's' ) ) ) {
    echo 'No search';
    exit;
}

$s = get_query_var( 's' );
echo $s;

Since there is no literal query string in the URL anymore and it has been redirected to a new URL with a different pattern where I won't be able to grab the value using $_GET['s']

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.