Woocommerce 404 ошибка категории товаров

Creating a perfect url structure can be pretty difficult with WooCommerce.

Download plugin

Solve 404 error caused by same shop base and category base conflict

Creating a perfect url structure can be pretty difficult with WooCommerce, specially if you try to set the same shop base and category base slug. This situation makes permalink structure conflict as WordPress is confused and doesn’t know which layout to generate: single-product or product-category page.

If you try to set up WooCommerce permalinks to get something like:

  • example.com/shop-name/ => Shop page listing products
  • example.com/shop-name/category-name/ => Category page listing products from a category (generates 404 error without this plugin)
  • example.com/shop-name/category-name/product-name/ => Product page showing product details

Setting the permalink structure this way is SEO friendly and sometimes your client may demand it, but you should avoid generating conflicts in code!

How to fix Woocommerce 404 error on category pages

Here are the permalink settings that we use to generate the ultimate url structure:

  • Shop base: my-shop
  • Product category base: my-shop (same as shop base)
  • Product permalink base: Shop base with category, e.g. my-shop/%product_cat%

ultimate woo url structure

Links generated:

www.site.com/my-shop/
=> Shop page listing products

www.site.com/my-shop/my-cat-1/
=> Category page listing products from a category (top-level category – 404 error)

www.site.com/my-shop/my-cat-1/sub-cat1/
=> 2nd level Category page(sub-category – 404 error)

www.site.com/my-shop/my-cat-1/sub-cat1/sub-sub-cat/
=> 3th level Category page(sub-sub-category – 404 error)

www.site.com/my-shop/my-cat-1/sub-cat1/sub-sub-cat/my-prod-3/
=> Single product from 3th level Category

Solution

So, we have to find a way to help WordPress distinguish categories from products.

Problem starts here www.site.com/my-shop/my-cat-1/ as obviously WordPress doesn’t know if “my-cat-1” is a product or category.

WP_Rewrite is WordPress’ class for managing the rewrite rules that allow you to use Pretty Permalinks feature. All rewrite rules are saved in database and all we have to do is to create a new rules for our site structure. We will not use general Regex syntax, but we will add a separate rewrite rule for every of our product categories.

This way we will tell WordPress how to resolve every single Product Category and this way we will avoid URL conflicts.

We made a plugin to work for you the way described. All you have to do is to upload and activate plugin. It will check if base and category structure are the same and will generate rewrite rule for all your Product Categories.

You can see on Status Page what’s done:

Simple as that!

Download plugin

Solve 404 error caused by same shop base and category base conflict

I am trying to set up WooCommerce permalinks to get something like:

  • example.com/shop/ => Shop page listing products
  • example.com/shop/category-name/ => Category page listing products from a category
  • example.com/shop/category-name/product-name/ => Product page showing product details

But I have a 404 not found error when trying to open the category page.

What I did is:

  • I created a «Shop» page and I set it as the shop page in WooCommerce settings. OK: The page works fine and is displaying all products.

  • In WordPress permalinks settings, I set the product category base to «shop». KO: When I try to display a category page, WP returns a 404 error (but links are properly generated in the shop page sidebar and 404 error occurs while clicking on them).

  • In WordPress permalinks settings, I set the product permalink to «/shop/%product_cat%». OK: Products pages are displaying without issue.

Any way to solve this?

Gabriel's user avatar

Gabriel

2,24810 gold badges21 silver badges24 bronze badges

asked Dec 23, 2015 at 17:26

Seb33300's user avatar

2

Under Custom Base where you have used /shop/%product_cat% needs to be replaced with /shop/%product-category% Please see screenshot below:

enter image description here

answered Dec 24, 2015 at 9:41

Prasad Nevase's user avatar

4

Turns out you don’t need to use %product-category% as this does create an issue with the permalinks, that variable name is left in the links, and not the actual product category.

Just leave Category base blank, that is what seems to have been causing the 404 error conflict. With the settings below, all is working:

example.com/store/ => Shop page listing products

example.com/store/category-name/ => Category page listing products from a category

example.com/store/category-name/product-name/ => Product page showing product details

enter image description here

answered May 16, 2017 at 17:29

i_a's user avatar

i_ai_a

3112 silver badges4 bronze badges

1

Creating a perfect url structure can be pretty difficult with WooCommerce.

Download plugin

Solve 404 error caused by same shop base and category base conflict

Creating a perfect url structure can be pretty difficult with WooCommerce, specially if you try to set the same shop base and category base slug. This situation makes permalink structure conflict as WordPress is confused and doesn’t know which layout to generate: single-product or product-category page.

If you try to set up WooCommerce permalinks to get something like:

  • example.com/shop-name/ => Shop page listing products
  • example.com/shop-name/category-name/ => Category page listing products from a category (generates 404 error without this plugin)
  • example.com/shop-name/category-name/product-name/ => Product page showing product details

Setting the permalink structure this way is SEO friendly and sometimes your client may demand it, but you should avoid generating conflicts in code!

How to fix Woocommerce 404 error on category pages

Here are the permalink settings that we use to generate the ultimate url structure:

  • Shop base: my-shop
  • Product category base: my-shop (same as shop base)
  • Product permalink base: Shop base with category, e.g. my-shop/%product_cat%

ultimate woo url structure

Links generated:

www.site.com/my-shop/
=> Shop page listing products

www.site.com/my-shop/my-cat-1/
=> Category page listing products from a category (top-level category – 404 error)

www.site.com/my-shop/my-cat-1/sub-cat1/
=> 2nd level Category page(sub-category – 404 error)

www.site.com/my-shop/my-cat-1/sub-cat1/sub-sub-cat/
=> 3th level Category page(sub-sub-category – 404 error)

www.site.com/my-shop/my-cat-1/sub-cat1/sub-sub-cat/my-prod-3/
=> Single product from 3th level Category

Solution

So, we have to find a way to help WordPress distinguish categories from products.

Problem starts here www.site.com/my-shop/my-cat-1/ as obviously WordPress doesn’t know if “my-cat-1” is a product or category.

WP_Rewrite is WordPress’ class for managing the rewrite rules that allow you to use Pretty Permalinks feature. All rewrite rules are saved in database and all we have to do is to create a new rules for our site structure. We will not use general Regex syntax, but we will add a separate rewrite rule for every of our product categories.

This way we will tell WordPress how to resolve every single Product Category and this way we will avoid URL conflicts.

We made a plugin to work for you the way described. All you have to do is to upload and activate plugin. It will check if base and category structure are the same and will generate rewrite rule for all your Product Categories.

You can see on Status Page what’s done:

Simple as that!

Download plugin

Solve 404 error caused by same shop base and category base conflict

Asked
7 years, 1 month ago

Viewed
25k times

I am trying to set up WooCommerce permalinks to get something like:

  • example.com/shop/ => Shop page listing products
  • example.com/shop/category-name/ => Category page listing products from a category
  • example.com/shop/category-name/product-name/ => Product page showing product details

But I have a 404 not found error when trying to open the category page.

What I did is:

  • I created a «Shop» page and I set it as the shop page in WooCommerce settings. OK: The page works fine and is displaying all products.

  • In WordPress permalinks settings, I set the product category base to «shop». KO: When I try to display a category page, WP returns a 404 error (but links are properly generated in the shop page sidebar and 404 error occurs while clicking on them).

  • In WordPress permalinks settings, I set the product permalink to «/shop/%product_cat%». OK: Products pages are displaying without issue.

Any way to solve this?

Gabriel's user avatar

Gabriel

2,23810 gold badges20 silver badges24 bronze badges

asked Dec 23, 2015 at 17:26

Seb33300's user avatar

2

Under Custom Base where you have used /shop/%product_cat% needs to be replaced with /shop/%product-category% Please see screenshot below:

enter image description here

answered Dec 24, 2015 at 9:41

Prasad Nevase's user avatar

4

Turns out you don’t need to use %product-category% as this does create an issue with the permalinks, that variable name is left in the links, and not the actual product category.

Just leave Category base blank, that is what seems to have been causing the 404 error conflict. With the settings below, all is working:

example.com/store/ => Shop page listing products

example.com/store/category-name/ => Category page listing products from a category

example.com/store/category-name/product-name/ => Product page showing product details

enter image description here

answered May 16, 2017 at 17:29

i_a's user avatar

i_ai_a

3012 silver badges4 bronze badges

1

Asked
7 years, 1 month ago

Viewed
25k times

I am trying to set up WooCommerce permalinks to get something like:

  • example.com/shop/ => Shop page listing products
  • example.com/shop/category-name/ => Category page listing products from a category
  • example.com/shop/category-name/product-name/ => Product page showing product details

But I have a 404 not found error when trying to open the category page.

What I did is:

  • I created a «Shop» page and I set it as the shop page in WooCommerce settings. OK: The page works fine and is displaying all products.

  • In WordPress permalinks settings, I set the product category base to «shop». KO: When I try to display a category page, WP returns a 404 error (but links are properly generated in the shop page sidebar and 404 error occurs while clicking on them).

  • In WordPress permalinks settings, I set the product permalink to «/shop/%product_cat%». OK: Products pages are displaying without issue.

Any way to solve this?

Gabriel's user avatar

Gabriel

2,23810 gold badges20 silver badges24 bronze badges

asked Dec 23, 2015 at 17:26

Seb33300's user avatar

2

Under Custom Base where you have used /shop/%product_cat% needs to be replaced with /shop/%product-category% Please see screenshot below:

enter image description here

answered Dec 24, 2015 at 9:41

Prasad Nevase's user avatar

4

Turns out you don’t need to use %product-category% as this does create an issue with the permalinks, that variable name is left in the links, and not the actual product category.

Just leave Category base blank, that is what seems to have been causing the 404 error conflict. With the settings below, all is working:

example.com/store/ => Shop page listing products

example.com/store/category-name/ => Category page listing products from a category

example.com/store/category-name/product-name/ => Product page showing product details

enter image description here

answered May 16, 2017 at 17:29

i_a's user avatar

i_ai_a

3012 silver badges4 bronze badges

1

add_filter( 'request', 'change_requerst_vars_for_product_cat' );
add_filter( 'term_link', 'term_link_filter', 10, 3 );
add_filter( 'post_type_link', 'wpp_remove_slug', 10, 3 );
add_action( 'pre_get_posts', 'wpp_change_request' );

function change_requerst_vars_for_product_cat($vars) {

    global $wpdb;
    if ( ! empty( $vars[ 'pagename' ] ) || ! empty( $vars[ 'category_name' ] ) || ! empty( $vars[ 'name' ] ) || ! empty( $vars[ 'attachment' ] ) ) {
      $slug   = ! empty( $vars[ 'pagename' ] ) ? $vars[ 'pagename' ] : ( ! empty( $vars[ 'name' ] ) ? $vars[ 'name' ] : ( ! empty( $vars[ 'category_name' ] ) ? $vars[ 'category_name' ] : $vars[ 'attachment' ] ) );
      $exists = $wpdb->get_var( $wpdb->prepare( "SELECT t.term_id FROM $wpdb->terms t LEFT JOIN $wpdb->term_taxonomy tt ON tt.term_id = t.term_id WHERE tt.taxonomy = 'product_cat' AND t.slug = %s", array( $slug ) ) );
      if ( $exists ) {
        $old_vars = $vars;
        $vars     = array( 'product_cat' => $slug );
        if ( ! empty( $old_vars[ 'paged' ] ) || ! empty( $old_vars[ 'page' ] ) ) {
          $vars[ 'paged' ] = ! empty( $old_vars[ 'paged' ] ) ? $old_vars[ 'paged' ] : $old_vars[ 'page' ];
        }
        if ( ! empty( $old_vars[ 'orderby' ] ) ) {
          $vars[ 'orderby' ] = $old_vars[ 'orderby' ];
        }
        if ( ! empty( $old_vars[ 'order' ] ) ) {
          $vars[ 'order' ] = $old_vars[ 'order' ];
        }
      }
    }

    return $vars;

  }

function term_link_filter( $url, $term, $taxonomy ) {

    $url = str_replace( "/product-category/", "/shop/", $url );
    return $url;

  }

function wpp_remove_slug( $post_link, $post, $name ) {

    if ( 'product' != $post->post_type || 'publish' != $post->post_status ) {
      return $post_link;
    }
    $post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );

    return $post_link;

  }

function wpp_change_request( $query ) {

    if ( ! $query->is_main_query() || 2 != count( $query->query ) || ! isset( $query->query[ 'page' ] ) ) {
      return;
    }
    if ( ! empty( $query->query[ 'name' ] ) ) {
      $query->set( 'post_type', array( 'post', 'product', 'page' ) );
    }

}

Перейти к содержимому

WooCommerce 404 ошибка

В этой записи я подробно расскажу о том как исправить частую ошибку после установления WooCommerce на вашем WordPress сайте.

Проблема не в том, что у вас что-то не так с шаблоном (по крайней мере я так думал изначально), а в установке плагина.

После некоторых обширных поисков в интернете на английских ресурсах, я нашел замечательную тему, в которой говорилось о решении данной проблемы.

Чтобы исправить эту проблему, вам нужно пройти в админ центр, далее «Настройки» -> «Постоянные ссылки» (как на сркиншоте ниже).

woocommerce 404

После того как нажали на «Постоянные ссылки», вам нужно спуститься до заголовка «Постоянные ссылки товаров» и выбрать пункт «Произвольная база» и в поле справа вставить /tovar/%product_cat%.

Вместо tovar вы можете написать что хотите, например produkt. Но ни в коем случае не стоит трогать %product_cat%, так как именно это и поможет вам решить проблему с 404 в WooCommerce.

Теперь мы можете посмотреть как выглядит ваша ссылка. Это должно быть прмерно так: /tovar/{имя_категории}/{название_вашего_товара}/.

На этом все. Если у вас есть какие-либо вопросы — пожалуйста задавайте их ниже под записью.

Об авторе

EXPLANATION OF THE ISSUE

I have my site running on the salient theme (completely updated to 8.0.15) running on Woocommerce v3.0.3 and the products are there in the woocommerce backend, they are there in the SQL database, and all the permalink settings are correct. However when you view the product page on the site, it shows a 404 error.

So far I have tried everything to fix it, including turning off all forms of caching plugin, turned off the theme and used the standard wordpress 2017 theme. I have turned off all plugins except woocommerce and the payment gateway stripe, but nothing works.

The site is hosted on godaddy, on a shared hosting package.

Interestingly, I have the same set up for another site, but which is hosted elsewhere and I can see the products just fine.

It can’t be the hosting causing the issue can it? If so, is there a known solution?

SYSTEM STATUS

«
### WordPress Environment ###

Home URL: https://www.discovergrandprix.com
Site URL: https://www.discovergrandprix.com
WC Version: 3.0.3
Log Directory Writable: ✔
WP Version: 4.7.3
WP Multisite: –
WP Memory Limit: 512 MB
WP Debug Mode: –
WP Cron: ✔
Language: en_GB

Server Environment

Server Info: Apache/2.4.25
PHP Version: 5.6.30
PHP Post Max Size: 8 MB
PHP Time Limit: -1
PHP Max Input Vars: 1000
cURL Version: 7.36.0
OpenSSL/1.0.1e

SUHOSIN Installed: –
MySQL Version: 5.6.33
Max Upload Size: 8 MB
Default Timezone is UTC: ✔
fsockopen/cURL: ✔
SoapClient: ✔
DOMDocument: ✔
GZip: ✔
Multibyte String: ✔
Remote Post: ✔
Remote Get: ✔

Database

WC Database Version: 3.0.3
WC Database Prefix: wp_
woocommerce_sessions: ✔
woocommerce_api_keys: ✔
woocommerce_attribute_taxonomies: ✔
woocommerce_downloadable_product_permissions: ✔
woocommerce_order_items: ✔
woocommerce_order_itemmeta: ✔
woocommerce_tax_rates: ✔
woocommerce_tax_rate_locations: ✔
woocommerce_shipping_zones: ✔
woocommerce_shipping_zone_locations: ✔
woocommerce_shipping_zone_methods: ✔
woocommerce_payment_tokens: ✔
woocommerce_payment_tokenmeta: ✔
MaxMind GeoIP Database: ✔

Security

Secure connection (HTTPS): ✔
Hide errors from visitors: ✔

Active Plugins (46)

Distance — Hotel to Track: by John McCurdy – 1.0
Facebook Page Box: by John McCurdy – 1.0
F1 Next race: by John McCurdy – 1.0.
Mid Article Sign Up: by John McCurdy. – 1.0.
Advanced Recent Posts: by Eugene Holin – 0.6.14
Contact Form 7 MailChimp Extension: by Renzo Johnson – 0.4.43
Contact Form 7: by Takayuki Miyoshi – 4.7
Disqus Comment System: by Disqus – 2.87
Duplicate Post: by Enrico Battocchi – 3.2
Instant Articles for WP: by Automattic
Dekode
Facebook – 3.3.3

Google XML Sitemaps: by Arne Brachhold – 4.0.8
Complete Analytics Optimization Suite (CAOS): by Daan van den Bergh – 1.44
Insert Headers and Footers: by WPBeginner – 1.4.2
Salient Visual Composer: by Michael M — WPBakery.com | Modified by ThemeNectar – 5.0.1
MailChimp for WooCommerce: by MailChimp – 1.1.1
MailChimp: by MailChimp – 1.5.7
Mapplic: by sekler – 4.1
Mashshare — Social Networks Add-On: by René Hermenau – 2.4.2
Mashshare Share Buttons: by René Hermenau – 3.4.1
Medium: by A Medium Corporation – 1.4.0
P3 (Plugin Performance Profiler): by GoDaddy.com – 1.5.3.9
PixelYourSite: by PixelYourSite – 5.0.2
WooCommerce Product Filter-Null24.Net: by Mihajlovic Nenad – 5.8.4
Printful Integration for WooCommerce: by Printful – 1.2.7
Publish to Apple News: by Alley Interactive – 1.2.5
Really Simple SSL: by Rogier Lankhorst – 2.5.11
Recent Posts Widget Extended: by Satrya – 0.9.9.6
Recent Posts Widget With Thumbnails: by Martin Stehle – 5.0
Regenerate Thumbnails: by Alex Mills (Viper007Bond) – 2.2.6
Social Count Plus: by Claudio Sanches – 3.3.5
SumoMe: by SumoMe – 1.25
Tawk.to Live Chat: by Tawkto – 0.2.5
Weather App: by John McCurdy – 1.0
Woocommerce Variations Table — Grid: by Spyros Vlachopoulos – 1.3.4
WooCommerce Cart Reports: by WPBackOffice – 1.1.8 – 1.1.13 is available
WooCommerce Save & Share Cart — NULL24.NET: by cxThemes – 2.10
WooCommerce Stripe Gateway: by WooCommerce – 3.1.6
WooCommerce Google Analytics Integration: by WooThemes – 1.4.0
Woocommerce Product Tabs: by Nilambar Sharma – 1.1
WooCommerce: by Automattic – 3.0.3
Yoast SEO: by Team Yoast – 4.6
WP All Export Pro: by Soflyy – 1.4.5
WP All Import Pro: by Soflyy – 4.3.0
WP Rocket | Shared By Themes24x7.com: by WP Rocket – 2.8.7
WP Smush: by WPMU DEV – 2.6.2
WP All Import — WooCommerce Add-On Pro: by Soflyy – 2.3.5

Settings

API Enabled: ✔
Force SSL: ✔
Currency: GBP (£)
Currency Position: left
Thousand Separator: ,
Decimal Separator: .
Number of Decimals: 0
Taxonomies: Product Types: bundle (bundle)
composite (composite)
external (external)
grouped (grouped)
simple (simple)
variable (variable)

Taxonomies: Product Visibility: exclude-from-catalog (exclude-from-catalog)
exclude-from-search (exclude-from-search)
featured (featured)
outofstock (outofstock)
rated-1 (rated-1)
rated-2 (rated-2)
rated-3 (rated-3)
rated-4 (rated-4)
rated-5 (rated-5)

WC Pages

Shop base: #6638 — /shop/
Basket: #164 — /cart/
Checkout: #165 — /checkout/
My account: #166 — /my-account/

Theme

Name: Salient
Version: 8.0.15
Author URL: http://themenectar.com
Child Theme: ❌ – If you’re modifying WooCommerce on a parent theme you didn’t build personally
then we recommend using a child theme. See: How to create a child theme

WooCommerce Support: ✔

Templates

Overrides: –
`

WooCommerce 404 errors can be common, especially when your plugin stack gets even mildly complex. One of the most common reasons for the 404 error is a failed automatic update or corrupt edit of the .htaccess file.

Reasons for the WooCommerce 404 Error

  1. A corrupt .htaccess file caused by a plugin, WooCommerce or WordPress itself
  2. You’ve added a category or attribute with the base ‘/product/’ which is in conflict with WooCommerce Product Permalink settings

Solving a Corrupt .htacess File Causing WooCommerce 404 Error – Short Term

Many WooCommerce and WordPress plugins add code to the .htaccess file and interact with the code placed within it.

Your WordPress Caching Plugin will be adding caching directives…

Your WordPress Security Plugin will be adding security protocols, whitelisted IPs etc…

Your core WooCommerce settings will be adding directives for permalink structures etc…

There’s a whole list

The great news is there’s a VERY simple fix to the WooCommerce 404 error when it’s caused by a corrupt .htaccess file.

If you can still login to the backend of WordPress:

  1. Head to Settings > Permalinks
  2. Click “Save” at the bottom of the page (no need to change anything)
  3. Flush the Cache for good measure
  4. Verify the fix has worked in incognito / from a different Wifi connection

If you can’t login to the backend of WordPress:

  1. Head over to your host and login
  2. Go to the “file manager” section (exact location will differ depending on which WooCommerce Host you’re using)
  3. Make a copy of the .htaccess file
  4. Rename the old .htaccess file to something like .htaccess1
  5. Copy and paste a default WordPress .htaccess file from here into your new .htaccess file
  6. Save the new .htaccess file
  7. Flush the cache from the hosting dashboard (if you can)
  8. Verify the fix has worked in incognito / from a different Wifi connection

Solving a Corrupt .htaccess File Causing WooCommerce 404 Problem – Long Term

As the solution basically involves “Clicking Save” on the Permalinks settings page inside WordPress, this is definitely something that can be automated.

So…

All you need to do is add a cron job to flush the .htaccess file frequently to limit the time for which the error can actually occurr.

What the hell is a cron job you say?

Don’t panic – all you ACTUALLY need to do is add a code snippet using the “Code Snippets” plugin and click “Save and Activate” and you’re DONE. NO Code knowledge necessary – it’s child’s play.

Here’s the code you need to add:

// Flush permalinks every hour 
add_action('my_hourly_event', 'do_this_hourly');
 
function my_activation() {
    if ( !wp_next_scheduled( 'my_hourly_event' ) ) {
        wp_schedule_event(time(), 'hourly', 'my_hourly_event');
    }
}
 
add_action('wp', 'my_activation');
 
function do_this_hourly() {
    global $wp_rewrite;
    $wp_rewrite->flush_rules();
}

Full credit for this code, and original source is isitwp.com – see the original code here

And here’s the code snippets plugin if you’ve not already got it installed:

Solving A Clash With A Category Or Attribute URL Base Causing WooCommerce 404 Error

As you’ll see on this drawn out thread on Github – this is more of a common caused of a WooCommerce 404 problem than I’d EVER have anticipated.

It basically means that an admin level user has intentionally created a “Post Category” or “Product Attribute” with the name “Product” – this means the slug for that category or attribute includes /product/ which is ALSO the default slug (permalink) for Product pages in WooCommerce.

This naturally leads to a conflict and means you’ve got a “human error” cause – and the technology hasn’t prevented that human error from occurring. Sometimes (a lot of the time) software just isn’t “poka yoke” and human error mistakes are allowed by the software when they shouldn’t be.

At some point in the future – this may well change and this error will become impossible – but for now, just watch out for rogue store owners and clients who could be causing some head scratching for you, the website manager!

I’m new in WooCommerce, and the last week i’m trying to solve problem with permalinks for WooCommerce in WP.
My client want a certain structure for products URL’s:
site.com/category/product or site.com/category/subcategory/product
In WP Permalinks settings I definite that structure:
Products Custom: /%product_cat%/%product%
In this case everything works fine except one thing, the URL of product page become:
site.com/category/product/product or site.com/category/subcategory/product/product/product
But if I setup this structure: /%product_cat% I just receive 404 on every product.
Sorry for my english, please help with that problem.

asked Aug 12, 2016 at 9:54

gugr's user avatar

2

Did you flush your permalinks after changing the settings?

There shouldn’t be any need to include %product%in the Product permalinks setting.

Simply use Custom: /%product_cat% and it should work.

answered Aug 12, 2016 at 18:55

dpruth's user avatar

dpruthdpruth

2744 silver badges16 bronze badges

add_filter( 'request', 'change_requerst_vars_for_product_cat' );
add_filter( 'term_link', 'term_link_filter', 10, 3 );
add_filter( 'post_type_link', 'wpp_remove_slug', 10, 3 );
add_action( 'pre_get_posts', 'wpp_change_request' );

function change_requerst_vars_for_product_cat($vars) {

    global $wpdb;
    if ( ! empty( $vars[ 'pagename' ] ) || ! empty( $vars[ 'category_name' ] ) || ! empty( $vars[ 'name' ] ) || ! empty( $vars[ 'attachment' ] ) ) {
      $slug   = ! empty( $vars[ 'pagename' ] ) ? $vars[ 'pagename' ] : ( ! empty( $vars[ 'name' ] ) ? $vars[ 'name' ] : ( ! empty( $vars[ 'category_name' ] ) ? $vars[ 'category_name' ] : $vars[ 'attachment' ] ) );
      $exists = $wpdb->get_var( $wpdb->prepare( "SELECT t.term_id FROM $wpdb->terms t LEFT JOIN $wpdb->term_taxonomy tt ON tt.term_id = t.term_id WHERE tt.taxonomy = 'product_cat' AND t.slug = %s", array( $slug ) ) );
      if ( $exists ) {
        $old_vars = $vars;
        $vars     = array( 'product_cat' => $slug );
        if ( ! empty( $old_vars[ 'paged' ] ) || ! empty( $old_vars[ 'page' ] ) ) {
          $vars[ 'paged' ] = ! empty( $old_vars[ 'paged' ] ) ? $old_vars[ 'paged' ] : $old_vars[ 'page' ];
        }
        if ( ! empty( $old_vars[ 'orderby' ] ) ) {
          $vars[ 'orderby' ] = $old_vars[ 'orderby' ];
        }
        if ( ! empty( $old_vars[ 'order' ] ) ) {
          $vars[ 'order' ] = $old_vars[ 'order' ];
        }
      }
    }

    return $vars;

  }

function term_link_filter( $url, $term, $taxonomy ) {

    $url = str_replace( "/product-category/", "/shop/", $url );
    return $url;

  }

function wpp_remove_slug( $post_link, $post, $name ) {

    if ( 'product' != $post->post_type || 'publish' != $post->post_status ) {
      return $post_link;
    }
    $post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );

    return $post_link;

  }

function wpp_change_request( $query ) {

    if ( ! $query->is_main_query() || 2 != count( $query->query ) || ! isset( $query->query[ 'page' ] ) ) {
      return;
    }
    if ( ! empty( $query->query[ 'name' ] ) ) {
      $query->set( 'post_type', array( 'post', 'product', 'page' ) );
    }

}

I’m new in WooCommerce, and the last week i’m trying to solve problem with permalinks for WooCommerce in WP.
My client want a certain structure for products URL’s:
site.com/category/product or site.com/category/subcategory/product
In WP Permalinks settings I definite that structure:
Products Custom: /%product_cat%/%product%
In this case everything works fine except one thing, the URL of product page become:
site.com/category/product/product or site.com/category/subcategory/product/product/product
But if I setup this structure: /%product_cat% I just receive 404 on every product.
Sorry for my english, please help with that problem.

asked Aug 12, 2016 at 9:54

gugr's user avatar

2

Did you flush your permalinks after changing the settings?

There shouldn’t be any need to include %product%in the Product permalinks setting.

Simply use Custom: /%product_cat% and it should work.

answered Aug 12, 2016 at 18:55

dpruth's user avatar

dpruthdpruth

2844 silver badges16 bronze badges

Возможно, вам также будет интересно:

  • Wolf e05 ошибка на котле
  • Wolfsp exe ошибка приложения
  • Wo mic ошибка подключения к серверу
  • Wolfenstein the old blood ошибка при запуске
  • Wo mic ошибка брандмауэра

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии