0

I want to change the search url of WordPress. Instead of url.com/?s=searchterm I want to change it to url.com/search/searchterm or url.com/search?s=searchterm.

On Google there's plenty of solutions for this, but most boil down to the following:

function wpb_change_search_url() {
    if ( is_search() && ! empty( $_GET['s'] ) ) {
        wp_redirect( home_url( "/search/" ) . urlencode( get_query_var( 's' ) ) );
        exit();
    }   
}
add_action( 'template_redirect', 'wpb_change_search_url' );

This works nice, but there's one caveat: if I open the page url.com/search,it gives me an error message. Whilst in the old situation url.com?s= gave me a page with 'type your query to search this search', now it gives a now found.

So my question is: how do I modify the above code, so that the page /search/ returns the same page as with an empty ?s=?

Many thanks!

1 Answer 1

0

Isn't that just because you've put ! empty( $_GET['s'] ) in your IF statement? Is your search page accessible when you remove that part?

EDIT:

Or maybe change your function to something like this (untested):

function wpb_change_search_url() {
    if ( is_search() ) {
        if ( isset( $_GET['s'] ) ) {
            wp_redirect( home_url( "/search/" ) . urlencode( get_query_var( 's' ) ) );
            exit();
        } else {
            wp_redirect( home_url( "/search/" ) );
            exit();
        }
    }   
}
add_action( 'template_redirect', 'wpb_change_search_url' );
6
  • Hey Delta, thanks for pointing that out. If I remove the condition, the search page is indeed not accessible anymore, the browser hangs.
    – ralphjsmit
    Aug 20, 2021 at 13:05
  • I just tested your solution, but strange this breaks the entire search. Even /search/searchterm doesnt work anymore..?
    – ralphjsmit
    Aug 20, 2021 at 13:06
  • Does it still break when you put the exit(); inside the IF and ELSE? On which URL do you end up? What do you see in your network tab?
    – DeltaG
    Aug 20, 2021 at 13:18
  • I tried your complete code snippet, I didn't try removing exit(). I must say that I now solved it by adding a page-search.php and in that file loading the search.php template. This solved it!
    – ralphjsmit
    Aug 20, 2021 at 13:21
  • Thanks for your time😁
    – ralphjsmit
    Aug 20, 2021 at 13:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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