0

Let me show you an example of what I'm trying to achieve. On BBC website when you click the search BBC button on the navbar it brings you to a search page (https://www.bbc.co.uk/search). When you put something in the search field (say apple) and hit enter the URL becomes (https://www.bbc.co.uk/search?q=apple&page=1) and this is exactly what I'm trying to achieve ( &page=1 is not required). So what I did is -

#1 first created a new page using pages -> add new option and titled it search and changed the default template to the search template search.php

2# I also have searchform.php serving as my custom search form template. Here is the code:

<form role="search" method="get" action="/search" id="search-form">
    <div class="search-field-wrapper">
        <label for="search-field" class="visually-hidden"><?php _ex( 'Search for:', 'label' );?></label>
        <input class="form-control" type="search" name="s" id="search-field" placeholder="<?php echo esc_attr_x( 'Search &hellip;', 'placeholder' ) ;?>" value="<?php echo get_search_query() ;?>">
        <span class="search-icon-wrapper"><i class="feather search-icon" data-feather="search"></i></span>
    </div>
</form>

When I'm searching for something the URL becomes http://localhost/search/?s=hello and getting 404 not found. So, how can I get it to work like the site I mentioned?

1 Answer 1

0

You can use the template_redirect action to add /search/ to your search URL's. Check out the code below:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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