url rewriting – Changing the wordpress default search url to something like – …example.com/search?query=keyword

Question

So I was trying to customize the WordPress default search URL and I found several solutions describing how to add a custom slug to the WordPress search URL and turn them into something like ...example.com/search/keyword. I tried the following solution:

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

It worked. But I want it to be something like ...example.com/search?query=keyword. I’ve updated the function:

function theme_change_search_url() {
        if ( is_search() && ! empty( $_GET['s'] ) ) {
            wp_redirect( home_url( "/search?query=" ) . urlencode( get_query_var( 's' ) ) );
            exit();
        }
    }

But it sends me to the 404 Not Found page. So how do I achieve the custom search URL?

0
Bipul Roy 1 year 2022-03-27T02:00:57-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse