• Hello!

    I’d like to change the default WordPress search URL. I was searching for a solution, found the code below on almost every site I visited:

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

    The code by itself works I guess, but the search now looks completely different than before, the whole search page is changed – instead of products being positioned normally, they are positioned below eachother. You can see this here.

    Let’s say for example that I’m searching for “Bazen”. The default search looks like /?s=bazen&post_type=product. What I’d like is just a simple /iskanje/bazen

    If I change /search/ in the code that I added to this request, I get the proper URL, but the page just shows 404 error.

    How can I edit this?

    Kind regards

    • This topic was modified 2 years, 2 months ago by jazzu.

    The page I need help with: [log in to see the link]

Viewing 2 replies - 16 through 17 (of 17 total)
  • Thread Starter jazzu

    (@jazzu)

    Hello again!

    Sorry for the late reply. I tried it on my staging website. I disabled all plugins except WooCommerce and changed the theme to Twenty Twenty-Two. The only code in functions.php is this:

    /*		Change search page slug.		*/
    
    function wpb_change_search_url() {
        if ( is_search() && ! empty( $_GET['s'] ) ) {
            wp_redirect( home_url( "/search/" ) . urlencode( get_query_var( 's' ) ) . '/?post_type=product' );
            exit();
        }   
    }
    add_action( 'template_redirect', 'wpb_change_search_url' );
    
    //enable /search/ path for products
    function custom_rewrite_rule() {
        add_rewrite_rule('^search\/([^/]*)\/?','index.php?post_type=product&s=$matches[1]','top');
    }
    add_action('init', 'custom_rewrite_rule', 10, 0 );

    Then, I went to settings, permalinks and just saved, without changing anything there. Went to the website and tried searching for something and still got /search/sesalnik/?post_type=product

    Kind regards and thank you very much for your time!

    Moderator bcworkz

    (@bcworkz)

    You shouldn’t need the template redirect related code in functions.php code any more. The added rewrite rule alone should handle it. You can disable it without removing it as a test by making the add_action() line into a comment.

    After changing the code, visit permalinks settings again. No need to save anything, simply requesting the screen is enough. No harm in saving though if it gives you more confidence that it’ll do something 🙂

Viewing 2 replies - 16 through 17 (of 17 total)
  • The topic ‘Changing search URL’ is closed to new replies.