Modify default WordPress search URL

By default WordPress search result page URL is a query parameter – ?s=[search_term]. Not a very “pretty” URL! But we can make it a nice “pretty” url with a little code snippet.

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

Above code will make your search page url from https://careless.dev/?s=[search_term] to https://careless.dev/search/[search_term].

But /search/ is the default slug for WordPress search results. So, what if you want to change /search/ to /something-else/. For that, we need to customize search_base property of WP_Rewrite class.

//first we set our new search slug
function careless_rewrite_search_slug() {
    global $wp_rewrite;
    $wp_rewrite->search_base = 'something-else';//edit something-else to whatever you want 
}
add_action( 'init', 'careless_rewrite_search_slug' );

//now we need to redirect ?s query to our new search slug
function careless_change_search_url() {
    if ( !is_admin() && is_search() && ! empty( $_GET['s'] ) ) {
        wp_redirect( home_url( "/something-else/" ) . urlencode( get_query_var( 's' ) ) ); 
        exit();
    }
}
add_action( 'template_redirect', 'careless_change_search_url' );

Code goes in the functions.php file of your active theme.

Now, since we have changed slug/permalink, we need to clear WordPress permalink cache for this change to start working. We can do that using flush_rules property of WP_Rewrite class. But there is no point to call it every time, when our code runs. Instead, we will clear this manually from WP Admin. Head to WP Admin > Settings > Permalinks and click on the Save Changes. You don’t really need to make any change – just a button click. That will clear permalink cache, and our new search slug will start working.