Callum
Callum

Reputation: 574

Woocommerce - Same Permalink for Shop, Category, Custom Base with Child Cats

my woocommerce website has the following structure:

  1. / = Homepage (Static Page)
  2. /products/ = Shop Page
  3. /products/ = Category Base
  4. /products/%product_cat% = Product Perma (custom base)

a url for a product becomes: website.com/products/parent/child/product-permalink

Currently the Shop Page abd Product Permalink works, along with the Parent Cat, but the child returns a 404.

Initially I had used this code in my functions.php

add_filter( 'rewrite_rules_array', function( $rules )
{
    $new_rules = array(
        'products/([^/]*?)/page/([0-9]{1,})/?$' => 'index.php?product_cat=$matches[1]&paged=$matches[2]',
        'products/([^/]*?)/?$' => 'index.php?product_cat=$matches[1]',
    );
    return $new_rules + $rules;
} );

Easy. Today I introduced Parent and Child categories. Snap!

I found the following post on SO: Woocommerce rewrite rule for product sub category

However, this doesn't do the trick, my configuration differs as I also have that Shop Page using the /Products location.

Can anyone see a quick fix?

Thank so much.

Upvotes: 2

Views: 1951

Answers (1)

Callum
Callum

Reputation: 574

Here's the trick, via - https://gist.github.com/levantoan/fc705c5ae4739e6d87e2ec51b257ea5c#file-set_product_category_base_same_shop_base-php

add_filter( 'rewrite_rules_array', function( $rules ) {
    $new_rules = array();
    $terms = get_terms( array(
        'taxonomy'   => 'product_cat',
        'post_type'  => 'product',
        'hide_empty' => false,
    ));
    if ( $terms && ! is_wp_error( $terms ) ) {
        $siteurl = esc_url( home_url( '/' ) );
        foreach ( $terms as $term ) {
            $term_slug = $term->slug;
            $baseterm = str_replace( $siteurl, '', get_term_link( $term->term_id, 'product_cat' ) );
            // rules for a specific category
            $new_rules[$baseterm .'?$'] = 'index.php?product_cat=' . $term_slug;
            // rules for a category pagination
            $new_rules[$baseterm . '/page/([0-9]{1,})/?$' ] = 'index.php?product_cat=' . $term_slug . '&paged=$matches[1]';
            $new_rules[$baseterm.'(?:feed/)?(feed|rdf|rss|rss2|atom)/?$'] = 'index.php?product_cat=' . $term_slug . '&feed=$matches[1]';
        }
    }

    return $new_rules + $rules;
} );

/**
 * Flush rewrite rules when create new term
 * need for a new product category rewrite rules
 */
function imp_create_term() {
    flush_rewrite_rules(false);;
}
add_action( 'create_term', 'imp_create_term' );

Simple, eh ;)

Upvotes: 1

Related Questions