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

Asked

Viewed
26k 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,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

2

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

}

Сегодня столкнулся с интересной проблемой в WordPress при задании определённой структуру url в WooCommerce.

Клиент захотел, чтобы структура url была такого вида:

http://сайт/shop/категория_товара/название_товара/

Если просто указать в настройках (Настройки -> Постоянные ссылки) нужную структуру, то все товары будут возвращать 404 ошибку.

Если Вы читаете это, значит проблема коснулась и Вас 🙂 Я попробовал даже пересоздать один товар, предполагая, что проблема только в существующих товарах. Но и новые товары так же возвращали ошибку 404.

Решение проблемы оказалось достаточно тривиальным: нужно просто сменить часть url SHOP на любое другое значение.

Например, вот так:
woocommerce-category-404-error

Всё сразу же заработало и выглядит красиво:
woocommerce-category-404-error-url

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

WooCommerce 404 ошибка

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

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

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

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

woocommerce 404

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

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

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

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

Об авторе

Понравилась статья? Поделить с друзьями:
  • Wmsd 601 ошибка f08
  • Wonderful whims ошибка
  • Word не удалось запуститься ошибка 24
  • Wmiprvse ошибка приложения
  • Word не сохраняет документ ошибка файла