url rewriting – How to change search page url so that it still returns a page when there’s no search query specified?


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' ) ) );
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!

ralphjsmit 1 year 2021-08-20T07:29:29-05:00 0 Answers 0 views 0

Leave an answer