Changing search slug from + to – (hyphen)

The question:

I’ve been fiddling with this all day, where I’m trying to change my search function from website.com/s?this%20is%20an%20example to website.com/tag/this-is-an-example to no avail.

I have this code in my snippets:

/** * Change search page slug. */

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

This is theoretically supposed to do what I want it to and I’m so close to solving this. But my urls now come out as /tag/this+is+an+example/ instead of /tag/this-is-an-example/

Any ideas? Any help is very much appreciated!

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

PHP’s urlencode() function replaces spaces with +s, so that’s why that’s happening for you.

WordPress provides the sanitize_title() function, which is used (among other things) to generate a post slug from the post’s title.

/** * Change search page slug. */

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment