Минимальная сумма корзины для подкатегорий определенной категории в WooCommerce

Я пытаюсь разрешить заказы только на сумму до 32 долларов для определенной категории (у нее есть несколько подкатегорий) или в комбинации из 4 подкатегорий (кофе1, популярные смеси, подписки, чай и шоколад).

На основании Минимальная сумма корзины для определенных категорий продуктов в Код ответа WooCommerce, вот мой код:

add_action( 'woocommerce_check_cart_items', 'check_cart_coffee_items' );
function check_cart_coffee_items() {
    $categories = array('coffee'); // Defined targeted product categories
    $threshold  = 32; // Defined threshold amount

    $cart       = WC()->cart;
    $cart_items = $cart->get_cart();
    $subtotal   = $cart->subtotal;
    $subtotal  -= $cart->get_cart_discount_total() + $cart->get_cart_discount_tax_total();
    $found      = false;

    foreach( $cart_items as $cart_item_key => $cart_item ) {
        // Check for specific product categories
        if ( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {
            $found = true; // A category is found
            break; // Stop the loop
        }
    }

    if ( $found && $subtotal < $threshold ) {
        // Display an error notice (and avoid checkout)
        wc_add_notice( sprintf( __( "You must order at least %s of coffee" ), wc_price($threshold) ), 'error' );
    }
}

Но я не могу заставить его работать ни для общей категории кофе, ни для каких-либо отдельных подкатегорий. Некоторая помощь приветствуется.


person Carin Lockhart    schedule 16.09.2020    source источник


Ответы (1)


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

add_action( 'woocommerce_check_cart_items', 'minimum_order_amount_for_subcategories' );
function minimum_order_amount_for_subcategories() {
    $term_slug   = 'coffee'; // <==  Define the targeted main product category slug
    $threshold   = 32; // <==  Define the minimum amount threshold

    $taxonomy    = 'product_cat'; // WooCommerce product category taxonomy
    $subtotal    = 0; // Itintializing
    $found       = false; // Itintializing
    
    // Get the children terms Ids from the main product category term slug
    $main_term   = get_term_by( 'slug', $term_slug, $taxonomy );
    $childen_ids = get_term_children( $main_term->term_id, $taxonomy );
    $terms_ids   = array_merge( array($main_term->term_id), $childen_ids);
    
    foreach( WC()->cart->get_cart() as $cart_item ) {
        // Check for specific product category children term ids
        if ( has_term( $terms_ids, $taxonomy, $cart_item['product_id'] ) ) {
            $found = true; // At least subcategory is found
            
            // Get non discounted subtotal including taxes from subcategories
            $subtotal += $cart_item['line_subtotal'] + $cart_item['line_subtotal_tax']; 
        }
    }

    if ( $found && $subtotal < $threshold ) {
        // Display an error notice (and avoid checkout)
        wc_add_notice( sprintf(
            __( "You must order at least %s of %s", "woocommerce" ),
            wc_price($threshold),
            '"<strong>' . ucfirst($term_slug) . '</strong>"' 
        ), 'error' );
    }
}

Код находится в файле functions.php вашей активной дочерней темы (или активной темы). он должен работать.

person LoicTheAztec    schedule 16.09.2020
comment
Хм, должно быть я что-то делаю не так. Я вставил код в свою дочернюю тему functions.php, но он не выдает сообщение, когда должно. Интересно, правильно ли настроены мои категории продуктов? Вот как они создаются: snipboard.io/ChXa3B.jpg. Может быть, лучше, если я сделаю основную категорию вместо родительской? - person Carin Lockhart; 17.09.2020