Redirect empty search to another page

Question

I am using the following code to change the url of my search results page:

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

It works perfectly. Now I want to redirect an empty search as well. Right now an empty search leads to /?s= but it should redirect to /suche. I managed to do the redirect but the browser shows a 404 for /suche.
I have tried every possible thing I could find online but nothing worked. Hopefully someone has an idea. Any help would be greatly appreciated!

My permalinks structure is /%postname% if that might be of importance.

0
, , , , Fabian Kleeberger 7 months 0 Answers 96 views 0

Leave an answer