Custom slug in front of search URL

I’ll try explain this the best I can…

I have a search form on my homepage:

<form role="search" method="get" id="searchform" class="form" action="<?php echo esc_url( home_url( "https://wordpress.stackexchange.com/" ) ); ?>">
    <label class="u-visuallyHidden" for="s">Search for property:</label>
    <input type="search" class="form-input search-bar-input" value="<?php echo get_search_query(); ?>" name="s" id="s" placeholder="enter location here" autocomplete="off" />

    <button type="submit" class="btn search-bar-btn" id="searchsubmit">
        <span class="u-verticalAlignMiddle"><i class="icon-search"></i> <span class="u-visuallyHidden">Search</span></span>
    </button>
</form>

And then there’s more in-depth search form in my ‘search.php’ template that holds a number of hidden fields that relate to some user input selectors. The search results then take the $_GET request and I build a custom $wp_query.

Everything works fine…but, I’d like to change my search URL to something like:

http://mydomain.dev/student/?s=

I’ve tried to change the action to esc_url( home_url( '/student/' ) ) but I just get a 404 when a search term is entered.

I’ve played around with the ‘template_redirect’ action and rewrite rules, but I don’t want pretty permalinks because my refined search form adds a number of additional URL params. For example a users search could yield this URL:

http://mydomain.dev/?s=&letmc_type=professional&custom_locations=SomeCity&min_bedrooms=2&price_min=60&price_max=70

Also, is there a better way with WordPress of utilizing query args, rather than the $_GET superglobal?

3 s
3

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.

Leave a Comment