WebMate
WebMate

Reputation: 95

Change search slug in wordpress

I try to edit the search slug in WordPress with this snippet :

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

And it works great. But i need to change the slug "/search/" to a custom and nothing work except this word. I get a 404 each time i change with others slugs.

Do you have any ideas on how can i achieve this please?

Thank you

Upvotes: 2

Views: 2213

Answers (3)

rheeantz
rheeantz

Reputation: 1020

You need to make a rewrite rule for your custom search slug / permalink

modify your code became like this

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

//additional rewrite rule + pagination tested
function rewrite_search_slug() {    
    add_rewrite_rule(
        'find(/([^/]+))?(/([^/]+))?(/([^/]+))?/?',
        'index.php?s=$matches[2]&paged=$matches[6]',
         'top'      
    );
}
add_action( 'init', 'rewrite_search_slug' );

Tested on local site. Change the word "find" with what you want, and dont forget to save permalink after adding this code within your theme function.

Upvotes: 1

Haninder Singh
Haninder Singh

Reputation: 618

Here is what I wrote on function.php:

function search_url_rewrite () {
if (is_search() && !empty($_GET['s'])) {
wp_redirect(home_url('/anything/').urlencode(get_query_var('s')));
exit();
}
}

add_action('template_redirect','search_url_rewrite');

Try this code..

Upvotes: 0

Dilip kumar
Dilip kumar

Reputation: 176

we have write script in php and .htaccess formate. please try any on of them..

php script

function fb_set_search_base() {

    $GLOBALS['wp_rewrite'] -> search_base = 'my_search'; // set new string
}
add_action( 'init', 'fb_set_search_base' );

htaccess script

  RewriteCond %{QUERY_STRING} s=(.*)
  RewriteRule ^$ /search/%1? [R,L]

For more information.. see here

Upvotes: 0

Related Questions