How to use shop in product category and product permalink in woocommerce

Created at 23-Aug-2023 , By samar

In this article, we'll explore how to leverage the "shop" structure in product categories and product permalinks within WooCommerce. These tactics not only enhance user-friendliness but also contribute to better search engine visibility.

Here is a step-by-step guide to incorporating "shop" into your URLs for both product categories and product detail pages.

  1. Access Permalink Settings: Begin by opening the Permalinks settings page. To do this, navigate to your WordPress dashboard and click on "Settings" then select "Permalinks".

  2. Update Product Category Base: On the Permalinks settings page, Look for the optional section. Instead of the default "product-category" change this to "shop" under the Product category base option.

  3. Optimize Product Permalinks: Continue by modifying the product permalinks. Under the same Permalinks settings page, Under the section of product permalinks. Choose the "Shop Base with Category" option. Once selected, you'll notice that the custom base input field will display /shop/%product_cat%/.

  4. Click on the save changes button.

  5. Open the functions.php file using a code editor of your choice. Once opened, you can simply copy and paste the provided code snippet below into the file. After pasting the code, ensure to save the functions.php file.

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

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.