How to change WP redirect on blog search?

I am running a WP Blog.
In permalinks I set WP base URL to https://www.url.com/blog.
That is necessary and can’t be changed.

If I try to use the WP-Search Widget for Blog it fails.
Because the URL WP is trying to redirect is wrong

Read More

(../blog/blog/?s=test).

Is there a way to say WP to use

../blog/?s=test

instead of

../blog/blog/?s=…

What I tried:
Put in functions.php this code (no success):

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

.htaccess can’t be changed

Ideas are highly appreciated.

Update to precise the question:

When investigating the search with Chrome, it shows that WP redirect the request.

If I only could prevent WP vom redirecting!

Chrome console output:

Remote Address:10.236.1.21:443
Request URL:https://www.domain.com/blog/?s=schnuffi
Request Method:GET
Status Code:302 Found
Response Headers
content-length:0
content-type:text/html; charset=UTF-8
date:Wed, 13 May 2015 08:52:46 GMT
location:https://www.domain.com/blog/blog/?s=schnuffi
server:nginx
status:302 Found
version:HTTP/1.1
….

Related posts

Leave a Reply

3 comments

  1. After removing the following function (I learnt you have implemented in your code):

    function change_blog_url() {
    if ( is_search() && ! empty( $_GET's' ) )
        { wp_redirect( home_url( "/blog/?s=" ) . urlencode( get_query_var( 's' ) ) ); exit(); }
    }
    

    WordPress should stop adding an additional “/blog” and the URL is resolved properly.

  2. Try to add the is_search() function into your condition. This function checks if search result page archive is being displayed. –> more at WordPress codex page

    And then try to add the exit() function into the end of your function.

    So your function may looks like:

    function fb_change_search_url_rewrite() {
      if ( is_search() && ! empty( $_GET['s'] ) ) {
        wp_redirect( site_url( "/" ) . urlencode( get_query_var( 's' ) ) ); exit();
      } 
    }
    
  3. In theme directory create file searchform.php and put
    this code in it:

    <form role="search" method="get" id="searchform" class="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>">
        <div>
            <label class="screen-reader-text" for="s"><?php _x( 'Search for:', 'label' ); ?></label>
            <input type="text" value="<?php echo get_search_query(); ?>" name="s" id="s" />
            <input type="submit" id="searchsubmit" value="<?php echo esc_attr_x( 'Search', 'submit button' ); ?>" />
        </div>
    </form>
    

    Change the form action attribute whatever you want, by default it will always print home url which will be your site url. eg: http://example.com/ so when your form get submitted it will make request to http://example.com?s=query.