мне нужно установить предел веса для корзины до 10 фунтов - PullRequest
0 голосов
/ 11 октября 2019

Мне нужно установить условие доставки, при котором общенациональная доставка недоступна для товара весом более 10 фунтов и показывает уведомление о том, что один товар в корзине не может быть отправлен по всей стране.

Я искал решение, но не повезло.

Я также попробовал приведенный ниже код, но он просто отменяет добавление в корзину, что пользователь даже не может ввести товар в корзину.

add_filter( 'woocommerce_add_to_cart_validation', 'custom_add_to_cart_validation', 20, 5 );
function custom_add_to_cart_validation( $passed, $product_id, $quantity, $variation_id = '', $variations = '' ) {
    // HERE define the weight limit per item
    $weight_limit = 2; // 2kg

    $total_item_weight = 0;

    // Check cart items
    foreach( WC()->cart->get_cart() as $cart_item ) {
        $item_product_id = empty($variation_id) ? $product_id : $variation_id;

        // If the product is already in cart
        if( $item_product_id == $cart_item['data']->get_id() ){
            // Get total cart item weight
            $total_item_weight += $cart_item['data']->get_weight() * $cart_item['quantity'];
        }
    }

    // Get an instance of the WC_Product object
    $product = empty($variation_id) ? wc_get_product($product_id) : wc_get_product($variation_id);

    // Get total item weight
    $total_item_weight += $product->get_weight() * $quantity;

    if( $total_item_weight > $weight_limit ){
        $passed = false ;
        $message = __( "Custom warning message for weight exceed", "woocommerce" );
        wc_add_notice( $message, 'error' );
    }

    return $passed;
}
//////////////
add_filter( 'woocommerce_after_cart_item_quantity_update', 'limit_cart_item_quantity', 20, 4 );
function limit_cart_item_quantity( $cart_item_key, $new_quantity, $old_quantity, $cart ){
    // HERE define the weight limit per item
    $weight_limit = 2; // 2kg

    // Get an instance of the WC_Product object
    $product = $cart->cart_contents[ $cart_item_key ]['data'];

    $product_weight = $product->get_weight(); // The product weight

    // Calculate the limit allowed max quantity from allowed weight limit
    $max_quantity = floor( $weight_limit / $product_weight );

    // If the new quantity exceed the weight limit
    if( ( $new_quantity * $product_weight ) > $weight_limit ){

        // Change the quantity to the limit allowed max quantity
        $cart->cart_contents[ $cart_item_key ]['quantity'] = $max_quantity;

        // Add a custom notice
        $message = __( "Custom warning message for weight exceed", "woocommerce" );
        wc_add_notice( $message, 'notice' );
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...