1

Why is it that when I attempt to change the URL for searches, it breaks if set to anything other than search?

function bfm_pretty_search () {

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

}
add_action('template_redirect', 'bfm_pretty_search');

So, instead of the url looking like mydomain.com/search/query, I'd like it to be: mydomain.com/results/query, but it doesn't work with anything other than "search"... why?

2 Answers 2

2

To change the search url hook in this function this will replace "search" to whatever you want.

add_action( 'init', 'wpse21549_init' );
function wpse21549_init()
{
    $GLOBALS['wp_rewrite']->search_base = 'results';
}

place this code in your functions.php file and after saving this file. Go to permalink settings page and click on the save button to flush the rewrite rules.

update

To modify the search rewrite rules you can hook into the search_rewrite_rules filter. You can either add the extra rewrite rules that match post types yourself, or you can change the default "search rewrite structure" to also include the post type and then re-generate the rules (there are four rules: one standard, one with paging and two for feeds).

add_filter( 'search_rewrite_rules', 'wpse15418_search_rewrite_rules' );
function wpse15418_search_rewrite_rules( $search_rewrite_rules )
{
    global $wp_rewrite;
    $wp_rewrite->add_rewrite_tag( '%post_type%', '([^/]+)', 'post_type=' );
    $search_structure = $wp_rewrite->get_search_permastruct();
    return $wp_rewrite->generate_rewrite_rules( $search_structure . '/section/%post_type%', EP_SEARCH );
}
2
  • 1
    I tried that, and resaved my permalink settings several times, and I can not get GLOBALS['wp_rewrite']->search_base to change from "search"
    – MultiDev
    Jan 18, 2017 at 6:43
  • Can you show me the code of your search form. May be you have hard coded it in form action. Because it should work in the normal wordpress scenario as i have tested it before. Jan 18, 2017 at 6:52
0

None of the above worked for me. Found another solution by overwriting the search rewrite rules using the search_rewrite_rules filter.

1 - Add this to the functions.php of your theme:

add_filter( 'search_rewrite_rules', function($rules) {
    
     $new_rules = [];

     // New search slug here
     $new_search_slug = 'zoeken';
    
     foreach ($rules AS $key => $value){
        
         $new_rules[str_replace('search', $new_search_slug, $key)] = $value;
        
     }

     return $new_rules;

});

2 - Save the permalinks in the WordPress admin under Settings -> Permalinks.

Now the page https://www.mywebsite.com/zoeken/searchterm is showing the search results page.

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.