Hi, I am looking to do the following in WooCommerce:
Before:
* **Product Category:** /product-category/category/
* **Subcategory:** /product-category/category/subcategory/
* **Single Product:** /product/product-category/sample-product/
After:
* **Product Category:** /category/
* **Subcategory:** /category/subcategory/
* **Single Product:** /product-category/sample-product-1/
​
The problem I am running into is that I can get it work for 2/3 combos and never 3/3.
For example, I can get it to do:
* **Product Category:** /category/
* **Single Product:** /product-category/sample-product-1/
but then **Subcategory:** /category/subcategory/ returns a 404.
Here’s the code I’m trying with:
// Remove the base from product category URLs
add_filter(‘term_link’, ‘custom_product_category_permalink’, 10, 3);
function custom_product_category_permalink($url, $term, $taxonomy) {
if ($taxonomy === ‘product_cat’) {
$url = str_replace(‘/product-category/’, ‘/’, $url);
}
return $url;
}
// Remove the base from product URLs
add_filter(‘post_type_link’, ‘custom_product_permalink’, 10, 2);
function custom_product_permalink($permalink, $post) {
if ($post->post_type === ‘product’) {
$permalink = str_replace(‘/product/’, ‘/’, $permalink);
}
return $permalink;
}
// Handle the redirection from the old URLs
function custom_redirect_old_urls() {
if (is_404()) {
$current_url = $_SERVER[‘REQUEST_URI’];
if (strpos($current_url, ‘/product-category/’) !== false) {
$new_url = str_replace(‘/product-category/’, ‘/’, $current_url);
wp_redirect(home_url($new_url), 301);
exit;
} elseif (strpos($current_url, ‘/product/’) !== false) {
$new_url = str_replace(‘/product/’, ‘/’, $current_url);
wp_redirect(home_url($new_url), 301);
exit;
}
}
}
add_action(‘template_redirect’, ‘custom_redirect_old_urls’);
// Add rewrite rules for products and product categories
function custom_rewrite_rules() {
// Rule for products
add_rewrite_rule(‘^([^/]*)/([^/]*)/?’, ‘index.php?product=$matches[2]’, ‘top’);
// Rule for product subcategories and categories
add_rewrite_rule(‘^([^/]*)/?’, ‘index.php?product_cat=$matches[1]’, ‘top’);
}
add_action(‘init’, ‘custom_rewrite_rules’);
All help is appreciated.
**Addendum:** I have pages created for Category and Subcategory that I am looking to have the default product category and subcategory direct to, so that I can custom make them using the editor.
Thanks.
[ad_2]