Reputation: 109
I set "Shop base with category" option in the Permalink Settings.
Now my product URLs are like that:
site.com/shop/category1/product1
However, this URL also goes to product1:
site.com/shop/randomword/product1
There is no category such "randomword" and also site.com/shop/randomword/ gives 404 error but the URL above works. It does not redirect to /category1/product1, it just works.
Therefore remove_filter( 'template_redirect', 'redirect_canonical' );
is not working. It works for other posts but not products.
Is there any way to prevent this?
Upvotes: 0
Views: 346
Reputation: 109
I found a solution for this.
The page works with a random category URL. So when the URL is not equal to permalink I decide to redirect to permalink. So when there is a random URL, it redirects to actual URL.
<?php
global $wp;
$current_url = home_url( $wp->request );
$actual_url = get_permalink();
if ((is_product()) && ($current_url !== $actual_url)) {
wp_redirect( $actual_url, 301 );
exit();
} ?>
You can put this code in the header.php
When you enter
site.com/shop/randomword/product1
it redirects to
site.com/shop/category1/product1
Edit:
The code breaks the draft preview. Need to specify it is published.
global $wp;
$current_url = home_url( $wp->request );
$actual_url = get_permalink();
$current_post_status = get_post_status();
if ((is_product()) && ($current_post_status == 'publish' ) && ($current_url !== $actual_url)) {
wp_redirect( $actual_url, 301 );
exit();
}
Upvotes: 0