0

I did some research but was unable to find a clue. Here is the scenario:

There is a product called "Album" which is assigned to both the "Music" & "Others" categories. The product permalink has been set to Custom base: /shop/%product_cat%/. Now, if I try to browse this product using the following URLs then both will work fine:

Not sure how WooCommerce is deciding the permalink but if I browse Music category then I'd expect that the product URL will be: http://dev.local/shop/music/album/ and if I browse Others category then I'd expect that the product URL will be: http://dev.local/shop/others/album/ respectively. But, it doesn't happen.

If I fetch the product using custom WP_Query based on product_cat then I can set my desired permalink.

Is there any other way that I can override the permalink based on the current product category?

Thank you!

1
  • Questions about third-party plugins are off-topic here and should be asked on the official WooCommerce support routes.
    – YourManDan
    Aug 17, 2023 at 15:41

1 Answer 1

0
function wpse264494_product_permalink( $permalink, $post ) {
    if ( 'product' === $post->post_type ) {
        $terms = get_the_terms( $post->ID, 'product_cat' );

        if ( $terms && ! is_wp_error( $terms ) ) {
            $category_slugs = wp_list_pluck( $terms, 'slug' );
            
            foreach ( $category_slugs as $category_slug ) {
                if ( strpos( $permalink, $category_slug ) !== false ) {
                    $loai = $category_slug;                    
                    break; 
                }
            }
            
            foreach ( $category_slugs as $category_slug ) {
                if ( strpos( $_SERVER['REQUEST_URI'], $category_slug ) !== false ) {
                    $new_permalink = str_replace( $loai, $category_slug, $permalink );
                    $permalink = $new_permalink;
                    break;
                }
            }
        }
    }

    return $permalink;
}
add_filter( 'post_type_link', 'wpse264494_product_permalink', 10, 2 );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.