Добавьте дополнительную плату в зависимости от категорий продуктов Woocommerce и страны пользователя.

Мне нужно добавить дополнительную плату в зависимости от категории и страны! Код хорошо работает со страной и отдельной категорией, но я не могу добавлять исключения для других категорий.

  1. Моя цель - создать дополнительную плату за средние пакеты в размере 30 евро с категорией (1,2,3) и дополнительную плату за большие пакеты в размере 50 евро с категорией (4,5,6), оба действительны для страны Европы.
  2. Дополнительная плата в размере 10 евро, посвященная Италии с категорией (1,2,3,4,5,6).

Вот мой код:

function df_add_ticket_surcharge_large( $cart_object ) {
global $woocommerce;

$specialfeecat = 1; // category id for the special fee
$spfee = 0.00; // initialize special fee
$spfeeperprod = 50; //special fee per product
$county = array('BE','EL','LT','PT','BG','ES','LU','RO','CZ','FR','HU','SI','DK','HR','MT','SK','DE','NL','FI','EE','CY','AT','SE','IE','LV','PL','UK');

foreach ( $cart_object->cart_contents as $key => $value ) {
    $proid = $value['product_id']; //get the product id from cart
    $quantiy = $value['quantity']; //get quantity from cart
    $itmprice = $value['data']->price; //get product price

    $terms = get_the_terms( $proid, 'article-type' ); //get taxonamy of the prducts
    if ( $terms && ! is_wp_error( $terms )) :
        foreach ( $terms as $term ) {
            $catid = $term->term_id;
            if($specialfeecat == $catid ) {
                $spfee = $spfeeperprod;
            }
        }
endif;  
}

if ( in_array( $woocommerce->customer->get_shipping_country(), $county ) ) {
    $woocommerce->cart->add_fee( 'Large Pack', $spfee, true, 'standard' );
    }
  }add_action('woocommerce_cart_calculate_fees','df_add_ticket_surcharge_large');

Кто-нибудь может мне помочь?


person Cristina Collins    schedule 04.04.2018    source источник
comment
У меня аналогичная проблема, но менее сложная: stackoverflow.com/questions/64117519/   -  person Julin Cicel    schedule 29.09.2020


Ответы (1)


Приведенный ниже код добавит прогрессивную комиссию за корзину в зависимости от страны и группы категорий товаров:

add_action('woocommerce_cart_calculate_fees', 'conditional_packing_fee', 20, 1 );
function conditional_packing_fee( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;

    // HERE the valid countries (including 'IT'):
    $valid_countries = array('BE','EL','LT','PT','BG','ES','LU','RO','CZ','FR','HU','SI','DK','HR',
    'MT','SK','DE','NL','FI','EE','CY','AT','SE','IE','LV','PL','UK','IT');
    $user_country = WC()->customer->get_shipping_country(); // Get the user shipping country

    if( ! in_array($user_country, $valid_countries) ) return; // Not a valid country, we EXIT

    // HERE your product categories groups:
    $product_cat1 = array(1,2,3,4,5,6); // Group 1 ==> cost 10
    $product_cat2 = array(4,5,6); // Group 2 ==> cost 30
    $product_cat3 = array(1,2,3); // Group 3 ==> cost 50

    $found1 = $found2 = $found3 = false;
    $fee = 0;

    foreach ( $cart->get_cart() as $cart_item ) {
        // Group 1 case
        if( has_term( $product_cat1, 'product_cat', $cart_item['product_id'] ) && 'IT' == $user_country ){
            $found1 = true;
            $break; // We can stop the loop for Italy (if found)
        } 
        // Group 2 case
        elseif( has_term( $product_cat2, 'product_cat', $cart_item['product_id'] ) && 'IT' != $user_country ){
            $found2 = true;
        } 
        // Group 3 case
        elseif( has_term( $product_cat3, 'product_cat', $cart_item['product_id'] ) && 'IT' != $user_country ){
            $found3 = true;
        }
    }
    if( $found1 ){
        $fee = 10; // Italy
        $label = __('Packing fee', 'woocommerce');
    } else {
        if( $found3 ){
            $fee = 50; // Large packs (can have medium packs too)
            $label = __('Large packs', 'woocommerce');
        } elseif( $found2 && ! $found3 ){
            $fee = 30; // Medium packs (only)
            $label = __('Large packs', 'woocommerce');
        }
    }

    if ( $fee > 0 )
        $cart->add_fee( $label, $fee, true, 'standard' );
}

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

person LoicTheAztec    schedule 05.04.2018