Andrii Kovalenko
Andrii Kovalenko

Reputation: 2227

How to redirect from one page to another one with changing wp query and without reloading page?

The problem

There is a URL: https://example.com/my-category/category

Need to create another one https://example.com/shop

Behavior to achieve:

By visiting https://example.com/shop content and all query variables need to be identical like for https://example.com/my-category/category

https://example.com/my-category/category and https://example.com/shop - need to be the same. Meta tags, title, and other content need to be identical.

Need to create an inner redirect

from https://example.com/shop

to https://example.com/my-category/category without reloading page.

This is the snippet what I've tried

flush_rewrite_rules(); add_rewrite_rule( '/shop?$', 'index.php?product_cat=my-category', 'top' );

I expect to see the same page for these two URLs

https://example.com/my-category/category and https://example.com/shop

The second one needs to be redirected to the first one.

Upvotes: 0

Views: 40

Answers (2)

Andrii Kovalenko
Andrii Kovalenko

Reputation: 2227

I have found a solution via request filter

function example_rewrite_request($query){
    $request_uri = urldecode( $_SERVER['REQUEST_URI'] );

    $parsed_url = parse_url( $request_uri );

    if (  preg_match( '/^\/shop/', $parsed_url['path'] ) ) {
        $query['product_cat'] = 'my-category';
        unset( $query['post_type'] );

        return $query;
    }

    return $query; 
}

add_filter( 'request', 'example_rewrite_request', 9999, 1 );

Upvotes: 0

chatnoir
chatnoir

Reputation: 2293

The easiest way to achieve this is to edit your .htaccess file (on your server, at the root folder for http://example.com) and add a 301 Redirect as follows:

Redirect 301 /shop /my-category/category

This means that when someone enters http://www.example.com/shop in the browser, it will be automatically redirected to http://www.example.com/my-category/category, and latter page will load.

Upvotes: 1

Related Questions