0

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!

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' );
1
  • 1
    Wow this is exactly what I needed, thank you!
    – Jey Pawlik
    May 13 at 21:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.