Как установить лимит покупок при оформлении заказа с минимальным требованием веса для определенной категории? - PullRequest
1 голос
/ 09 мая 2020

Я пытаюсь установить лимит покупок перед оформлением заказа, а именно:

  • Требование минимального веса для категории ' formaggi '

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

Я использую этот фрагмент, но он не работает ни с категорией, ни с требованиями минимального веса.

/*PESO MINIMO CATEGORIA FORMAGGI 750GR - RAFFO 14mar2020*/
add_action( 'woocommerce_check_cart_items', 'cldws_set_weight_requirements' );
function cldws_set_weight_requirements() {
    // Only run in the Cart or Checkout pages
    if( is_cart() || is_checkout() || is_product () && has_term( ‘formaggi’, ‘product_cart’ )) {
        global $woocommerce;

        // Set the minimum weight before checking out
        $minimum_weight = 0.750;

        // Get the Cart's content total weight per categoria
        $cart_contents_weight = WC()->cart->cart_contents_weight;

        // Compare values and add an error is Cart's total weight
        if( $cart_contents_weight < $minimum_weight  ) {
            // Display our error message
            wc_add_notice( sprintf('<strong>Per i Formaggi è richiesto un acquisto minimo di %s gr.</strong>'
            . '<br />Peso dei Formaggi nel carrello: %s gr',
            $minimum_weight*1000,
            $cart_contents_weight*1000,
            get_option( 'woocommerce_weight_unit' ),
            get_permalink( wc_get_page_id( 'shop' ) )
            ), 'error' );
        }
    }
}

Кто-нибудь, кто знает, что я делаю неправильно или где что-то не так?

1 Ответ

1 голос
/ 10 мая 2020

В вашем коде есть ошибки.

Следующий код проверяет требования к минимальному весу для категории 'formaggi', комментарий с пояснением, добавленным между строками кода

function cldws_set_weight_requirements() {
    // Only on cart and check out pages
    if( ! ( is_cart() || is_checkout() ) ) return;

    /* SETTINGS */

    // The minimum weight
    $minimum_weight = 20; // 20 kg

    // Set term (category)
    $term = 'formaggi';

    /* END SETTINGS */

    // Set variable
    $found = false;

    // Total weight
    $total_weight = 0;

    // Loop through cart items        
    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {        
        // Product id
        $product_id = $cart_item['product_id'];

        // Quantity
        $product_quantity = $cart_item['quantity'];

        // Get weight
        $product_weight = $cart_item['data']->get_weight();

        // NOT empty & has certain category
        if ( ! empty( $product_weight ) && has_term( $term, 'product_cat', $product_id ) ) {
            // The shopping cart contains a product of the specific category
            $found = true;

            // Calculate
            $total_weight += $product_quantity * $product_weight;
        }
    }

    // If the total weight is less than the minimum and there is a item in the cart from a specific category
    if( $total_weight < $minimum_weight && $found ) {
        // Displays a dynamic error warning
        wc_add_notice( sprintf(
            'The minimum weight for the "%s" category is %s, you currently have %s',
            $term,
            wc_format_weight($minimum_weight),
            wc_format_weight($total_weight)
        ), 'error' );

        // Removing the proceed button, until the condition is met
        remove_action( 'woocommerce_proceed_to_checkout','woocommerce_button_proceed_to_checkout', 20);
    }
}
add_action( 'woocommerce_check_cart_items', 'cldws_set_weight_requirements' );
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...