Восстановить цену товара со скидкой для определенного способа доставки в Woocommerce - PullRequest
0 голосов
/ 25 августа 2018

Я пытаюсь найти решение следующей проблемы. Я использую динамическое ценообразование Woocommerce, чтобы применить скидку 25% для определенной категории продуктов. Затем мне нужно удалить эту скидку, если вариант доставки будет local_pickup. Я думал, что могу настроить следующий код. Где-то чего-то не хватает, поэтому я прошу вас о помощи.

function discount_table(){
// Set $cat_in_cart to false
$cat_in_cart = false;

// Loop through all products in the Cart        
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {

    if ( has_term( 'category_1', 'product_cat', $cart_item['product_id'] ) ) {
        $cat_in_cart = true;
        break;
    }
}

    $total = WC()->cart->subtotal;
    $sconto_label = "";
    if($total >= 300){
        $sconto_label=15;       
    }elseif($total >= 220){
        $sconto_label=10;
    }elseif($total >= 150){
        $sconto_label=8;
    }elseif($total >= 100){
        $sconto_label=4;
    }
    $chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
    $chosen_shipping = explode(':',$chosen_methods[0]);

    if($chosen_shipping[0]=='local_pickup' && !$cat_in_cart){
        $sconto_label=25;
    }
    else if ($chosen_shipping[0]=='local_pickup' && $cat_in_cart){
        $sconto_label=25;
// there should be something here or not?
    }
    $sconto_cliente = (($total*$sconto_label)/100);
    if($sconto_label!="")
        $sconto_cliente_net = ($sconto_loison/1.1);
        WC()->cart->add_fee( "Discount ($sconto_label%)", -$sconto_cliente_net, false );
}
add_action( 'woocommerce_cart_calculate_fees','discount_table' );

Есть ли способ восстановить первоначальную цену одного или нескольких предметов определенной категории, которые уже были уценены в корзине?

Ответы [ 2 ]

0 голосов
/ 12 сентября 2018

Я немного покопался в вашем коде и внес некоторые изменения.Нашел ошибку благодаря супер дев!Вот код:

function discount_table(){
$cat_in_cart = false;
$tot_cat = 0;
foreach ( WC()->cart->get_cart() as $cart_item ) {

    if ( has_term( 'cat1', 'product_cat', $cart_item['product_id'] ) ) {
        $cat_in_cart = true;
        $tot_cat_price = $cart_item['data']->get_price();
        $tot_cat_qty = $cart_item['quantity'];
        $tot_cat +=  $tot_cat_price * $tot_cat_qty;
        //break;
/* commented here, thanks to Michael Ramin: break will stop execution of the loop after found the first product belonging to the category; what if you have more than one? so remove break instruction */
    }
}
    global $product;
    $total = WC()->cart->subtotal;
    $discount_label = "";
    if($total >= 300){
        $discount_label=15;     
    }elseif($total >= 220){
        $discount_label=10;
    }elseif($total >= 150){
        $discount_label=8;
    }elseif($total >= 100){
        $discount_label=4;
    }
    $chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
    $chosen_shipping = explode(':',$chosen_methods[0]);

    if($chosen_shipping[0]=='local_pickup'){
        $discount_label=25;
    }
    $discount_brand = ($total-$tot_cat)*$discount_label/100;
    if($discount_label!=""){
        $discount_brand_net = ($discount_brand/1.1);
        if($discount_brand_net != 0) // show discount only if != 0; it may happen if cart includes only targeted category products;
            WC()->cart->add_fee( "Discount ($discount_label%)", -$discount_brand_net, false );
    }   
}
add_action( 'woocommerce_cart_calculate_fees','discount_table' );
0 голосов
/ 25 августа 2018

Чтобы восстановить цену товаров в корзине на основе категории продукта и выбранного метода доставки, попробуйте следующее (для динамического ценообразования Woocommerce) :

add_filter('woocommerce_add_cart_item_data', 'add_default_price_as_cart_item_custom_data', 50, 3 );
function add_default_price_as_cart_item_custom_data( $cart_item_data, $product_id, $variation_id ){
    // HERE define your product category(ies)
    $categories = array('t-shirts');

    if ( has_term( $categories, 'product_cat', $product_id ) ) {
        $product_id = $variation_id > 0 ? $variation_id : $product_id;

        // The WC_Product Object
        $product = wc_get_product($product_id);

        // Get product default base price
        $price = (float) $product->get_price();

        // Set the Product default base price as custom cart item data
        $cart_item_data['default_price'] = $price;
    }
    return $cart_item_data;
}

add_action( 'woocommerce_before_calculate_totals', 'restore_cart_item_price', 900, 1 );
function restore_cart_item_price( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // HERE set the targeted Chosen Shipping method
    $targeted_shipping_method = 'local_pickup';

    // Get the chosen shipping method
    $chosen_methods            = WC()->session->get( 'chosen_shipping_methods' );
    $chosen_shipping_method_id = explode(':', reset($chosen_methods) );
    $chosen_shipping_method    = reset($chosen_shipping_method_id);

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item ) {
        if( $targeted_shipping_method == $chosen_shipping_method && isset($cart_item['default_price']) ){
            // Set back the default cart item price
            $cart_item['data']->set_price($cart_item['default_price']);
        }
    }
}

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

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...