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!
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
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