最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Woocommerce redirection product_name -> product_catproduct_name

programmeradmin0浏览0评论

First, the product url was /product_name. But the boss wished to change it to product_cat/product_name. Where product_cat is the primary category. So the plugin Premmerce has been installed and the new url are correct. But, Google has already indexed product pages with the previous url. Thus, i need to redirect all old url to new. For example / to / The plugin Redirection was already installed so I tried with a new redirection : /%product_name% to /%product_cat%/%product_name% But it doesn't work.

So I tried with .htaccess with adding : Redirect 301 /%product_name% /%product_cat%/%product_name% It doesn't work :-(

How can I do ???

Thanks a lot for your help !

First, the product url was /product_name. But the boss wished to change it to product_cat/product_name. Where product_cat is the primary category. So the plugin Premmerce has been installed and the new url are correct. But, Google has already indexed product pages with the previous url. Thus, i need to redirect all old url to new. For example http://chaiseguy.kamilane.odns.fr/abstrait-2/ to http://chaiseguy.kamilane.odns.fr/t-shirts/abstrait-2/ The plugin Redirection was already installed so I tried with a new redirection : /%product_name% to /%product_cat%/%product_name% But it doesn't work.

So I tried with .htaccess with adding : Redirect 301 https://chaiseguy.kamilane.odns.fr/%product_name% https://chaiseguy.kamilane.odns.fr/%product_cat%/%product_name% It doesn't work :-(

How can I do ???

Thanks a lot for your help !

Share Improve this question asked Aug 17, 2020 at 18:47 user2898349user2898349 211 silver badge4 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

You could try the template_redirect action. Check if current request is a single product. @see https://codex.wordpress/Plugin_API/Action_Reference/template_redirect

add_action( 'template_redirect', function() {

    //= bail early
    if( !is_404() ) return;

    //= get product name from url
    $product_name = get_query_var( 'pagename' );

    //= bail
    if( empty( $product_name ) ) return;

    //= lookup product by name
    $product = get_page_by_path( $product_name, OBJECT, 'product' );

    //= bail
    if( is_null( $product ) ) return;

    //= redirect
    wp_redirect( get_the_permalink( $product->ID ) );
    exit;

} );

Note #1 in addition you might want to check if query_var "product_cat" is empty. Otherwise you might end up with an infinite loop.

Note #2 try to add some logic ( add it if it doesn't exist, otherwise skip logic ) to pass the redirect to the Redirection plugin. Idea above will run on every request. If it's just a redirect sitting in the Redirection plugin, it will be faster.

Hope this sets you on the right track. Sorry I don't have the exact solution.

发布评论

评论列表(0)

  1. 暂无评论