Many webmasters, when creating an online store with WooCommerce, face the task of creating clean, human-readable URLs. In other words, correct structure. Unfortunately, the engine works a bit differently. It is important to note that this method will work on multilingual sites, for example, those using the WPML plugin.
So, here’s a guide on how to make these URLs:
1 2 3 |
Shop page: http://domain.com/shop/ Category: http://domain.com/shop/your-category Product page: http://domain.com/shop/your-category/your-sample-product |
Assign the shop link to the shop page.
Go to Settings – Permalinks and set the following parameters:
1 2 |
Product category base – shop Custom base – /shop/%product_cat%/ |
Add the following code to the theme’s functions.php file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
add_filter( 'init', 'ywp_product_category_base_same_shop_base' ); function ywp_product_category_base_same_shop_base( $flash = false ){ global $sitepress; $languages = icl_get_languages( 'skip_missing=0&orderby=code' ); if( $languages && ! empty( $languages ) ){ $original_lang = ICL_LANGUAGE_CODE; foreach( $languages as $key=>$lang ) { $new_lang = $key; $sitepress->switch_lang( $new_lang ); $terms = get_terms( array( 'taxonomy' => 'product_cat', 'post_type' => 'product', 'hide_empty' => false, ) ); if ( $terms && ! is_wp_error($terms ) ) { $siteurl = apply_filters( 'wpml_home_url', get_home_url( '/' ) ); $siteurl = ( $sitepress->get_default_language() == $key ) ? $siteurl.'/' : $siteurl; foreach ( $terms as $term ) { $term_slug = $term->slug; $baseterm = str_replace( $siteurl, '', get_term_link($term->term_id, 'product_cat' ) ); add_rewrite_rule( $baseterm . '?$', 'index.php?product_cat=' . $term_slug, 'top' ); add_rewrite_rule( $baseterm . 'page/([0-9]{1,})/?$', 'index.php?product_cat=' . $term_slug . '&paged=$matches[1]', 'top' ); add_rewrite_rule( $baseterm . '(?:feed/)?(feed|rdf|rss|rss2|atom)/?$', 'index.php?product_cat=' . $term_slug . '&feed=$matches[1]', 'top' ); } } $sitepress->switch_lang( $original_lang ); } } if ( $flash == true ) flush_rewrite_rules( false ); } /* Fix error when creating new taxomony is 404 */ add_action( 'create_term', 'ywp_product_cat_same_shop_edit_success', 10, 2 ); function ywp_product_cat_same_shop_edit_success( $term_id, $taxonomy ) { ywp_product_category_base_same_shop_base( true ); } |
Just in case, hit save again in the permalink settings, and enjoy the results.
Now your links will have the correct structure, and there will be no 404 errors when navigating to subcategories.
Leave a Reply