How can I have shop base and product base the same in Woocommerce
Asked Answered
G

2

1

I am trying to have the same shop base and the same product base at the same time. The format I am trying to have is:

website.com/shop/shoes/blue-suede-shoes/

I came across this code that makes it work so far with just a small glitch:

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;
} );

function imp_create_term() {
    flush_rewrite_rules(false);;
}
add_action( 'create_term', 'imp_create_term' );

Every single path works as desired, except when I try to open:

website.com/shop/shoes/page/2 which returns a page not found error

this path works well tough:

website.com/shop/page/2

What am I missing? Does WP interprets "page" as a subcategory? How can I fix this?

Thank you

Gracchus answered 10/2, 2020 at 21:53 Comment(2)
Cant you just do this with permalinks under settings?Thesis
Unfortunately it doesn't work.. not even to make it so far..Gracchus
T
0

Posting this as answer so I can include a screenshot for you.

1) Go to yourwebsite.com/wp-admin/options-permalink.php

2) Under Product Permalinks select Shop Base with Category. This will work for product level.

woocommerce example

3) Set the product category base to something like /shop/product-category

WC Permalink Docs

Don't forget to remove your custom code.

Thesis answered 10/2, 2020 at 23:14 Comment(0)
Y
0

You can just add this little coed snippets in your functions.php

add_filter( 'rewrite_rules_array', function( $rules )
{
    $new_rules = array(
        'shop/([^/]*?)/page/([0-9]{1,})/?$' => 'index.php?product_cat=$matches[1]&paged=$matches[2]',
        'shop/([^/]*?)/?$' => 'index.php?product_cat=$matches[1]',
    );
    return $new_rules + $rules;
} );
Yulandayule answered 12/8, 2022 at 11:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.