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

Я бы хотел, чтобы клиент не перешел на проверку, если у них нет определенной категории товаров в корзине. Я также хотел бы сообщить им сообщение об ошибке, что им нужно добавить определенный продукт. Я нашел код, но не могу работать. Я добавил его как фрагмент кода в мою установку WordPress, но, увы, он не работает, и нет сообщений об ошибках, даже если у меня включена отладка. Вот код, который я нашел в Github, который может нуждаться в модификации, чтобы это работало:

function sv_wc_prevent_checkout_for_category() { // set the slug of the category for which we disallow checkout $category = 'sibling'; // get the product category $product_cat = get_term_by( 'slug', $category, 'product_cat' ); // sanity check to prevent fatals if the term doesn't exist if ( is_wp_error( $product_cat ) ) { return; } $category_name = '<a href="' . get_term_link( $category, 'product_cat' ) . '">' . $product_cat->name . '</a>'; // check if this category is the only thing in the cart if ( sv_wc_is_category_alone_in_cart( $category ) ) { // render a notice to explain why checkout is blocked wc_add_notice( sprintf( 'Hi there! Looks like your cart only contains products from the %1$s category &ndash; you must purchase a product from another category to check out.', $category_name ), 'error' ); } } add_action( 'woocommerce_check_cart_items', 'sv_wc_prevent_checkout_for_category' ); /** * Checks if a cart contains exclusively products in a given category * * @param string $category the slug of the product category * @return bool - true if the cart only contains the given category */ function sv_wc_is_category_alone_in_cart( $category ) { // check each cart item for our category foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) { // if a product is not in our category, bail out since we know the category is not alone if ( ! has_term( $category, 'product_cat', $cart_item['data']->id ) ) { return false; } } // if we're here, all items in the cart are in our category return true; } 

Поэтому я хочу остановить проверку (с сообщением об ошибке), если категория «sibling» является единственным элементом в корзине. У меня есть «стандартная» категория, которая должна быть в корзине, прежде чем клиент отправит ее в кассу. Надеюсь, это имеет смысл.

Здесь у вас есть решение, которое сделает трюк. Существует особенно две основные функции (последние) :

  1. Первая функция (N ° 3) отображает ваше сообщение на странице корзины, если в теле есть что-то, но не обязательная категория продукта. Отображает также сообщение на страницах обязательного архива продукта (полезно, когда клиент получает перенаправление из проверки, см. Ниже) .
  2. Вторая функция (N ° 4) перенаправляет клиента на страницы обязательной категории продуктов, когда она пытается проверить, а в его тележке отсутствует пропущенная обязательная категория продукта.

Определите перед своей обязательной категорией slug в your_mandatory_category_slug() .

Это код:

 // Function that define the mandatory product category function your_mandatory_category_slug(){ // DEFINE HERE the SLUG of the needed product category $category = 'clothing'; return $category; } // Conditional function that returns true if the mandatory product category is in cart function has_mandatory_category(){ $category_needed = your_mandatory_category_slug(); $has_cat = false; // Iterrating each item in cart and detecting… foreach ( WC()->cart->get_cart() as $item ) { // Detects if the needed product category is in cart items if ( has_term($category_needed, 'product_cat', $item['product_id'] ) ) { $has_cat = true; break; } } return $has_cat; } // Function that display a message if there is not in cart a mandatory product category function mandatory_category_display_message() { $category_needed = your_mandatory_category_slug(); // check that cart is not empty (for cart and product category archives) if( !WC()->cart->is_empty() && ( is_cart() || is_product_category( $category_needed ) ) ){ $category_obj = get_term_by( 'slug', $category_needed, 'product_cat' ); if ( is_wp_error( $category_obj ) ) return; // Display message when product category is not in cart items if ( !has_mandatory_category() ) { $category_name = $category_obj->name; $category_url = get_term_link( $category_needed, 'product_cat' ); // render a notice to explain why checkout is blocked wc_add_notice( sprintf( __( '<strong>Reminder:</strong> You have to add in your cart, a product from "%1$s" category, to be allowed to check out. Please return <a href="%2$s"> here to "%1$s" product page</a>', 'your_theme_domain'), $category_name, $category_url ), 'error' ); } } } add_action( 'woocommerce_before_main_content', 'mandatory_category_display_message', 30 ); // for product mandatory category archives pages add_action( 'woocommerce_check_cart_items', 'mandatory_category_display_message' ); // for cat page // Function that redirect from checkout to mandatory product category archives pages function mandatory_category_checkout_redirect() { // If cart is not empty on checkout page if( !WC()->cart->is_empty() && is_checkout() ){ $category_needed = your_mandatory_category_slug(); // If missing product category => redirect to the products category page if ( !has_mandatory_category() ) wp_redirect( get_term_link( $category_needed, 'product_cat' ) ); } } add_action('template_redirect', 'mandatory_category_checkout_redirect'); 

Это происходит в файле function.php вашей активной дочерней темы (или темы), а также в любом файле плагина.

Этот код проверен и полностью работоспособен.