Monday, September 29, 2014

Woocommerce issue when products and categories has same base path

404 on Product detail page?

Ran into this issue where I needed a url structure such as/shop/<category> and /shop/<category>/<product>/.

/shop/<category>/ works fine but once you click a product you get a nice looking 404 page.

My settings:
Product category base - /shop
Product permalink base -> Custom Structure - /shop/%product_cat%

The Fix:

Set the ‘Product category base’ to shop and the custom product base to /shop/%product_cat%.
Then in your functions.php file add this little snippet:

<?php
add_filter('request', function( $request ) {
     $tax_qv = 'product_cat';
     $cpt_name = 'product';

     if(!empty( $request[$tax_qv])) {
          $slug = basename($request[$tax_qv]);

          // if this would generate a 404
         if(!get_term_by('slug', $slug, $tax_qv)) {
              // set the correct query vars
              $request['name'] = $slug;
              $request['post_type'] = $cpt_name;
              unset($request[$tax_qv]);
         }
     }
     return $request;
});


No comments:

Post a Comment