Прогрессивная плата за товар в корзине в зависимости от состояния и категории продукта в Woocommerce.

Недавно я попытался использовать 2 снайперских кода в одном для этого проекта Woocommerce, где мне нужно установить плату за конкретную категорию продукта (идентификатор термина: 19) и конкретный штат страны (Флорида 'FL')

Кроме того, мне нужно умножить эту ставку на товары из этой категории продуктов (19).

Это мой настоящий код:

add_action('woocommerce_cart_calculate_fees','woocommerce_custom_surcharge'); 
function woocommerce_custom_surcharge() {
    $category_ID = '19'; 

    global $woocommerce;


    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    $state  = array('FL');


    foreach ($woocommerce->cart->cart_contents as $key => $values ) {
    // Get the terms, i.e. category list using the ID of the product

    $terms = get_the_terms( $values['product_id'], 'product_cat' );
    // Because a product can have multiple categories, we need to iterate through the list of the products category for a match
    foreach ($terms as $term) 
    {
        // 19 is the ID of the category for which we want to remove the payment gateway
        if($term->term_id == $category_ID){
    $surcharge  = 1;

    if ( in_array( WC()->customer->shipping_state, $state && ) ) {
        $woocommerce->cart->add_fee( 'State Tire Fee', $surcharge, true, '' );
    }
}

Как я могу установить прогрессивную плату на основе товаров из определенной категории и клиентов из определенного штата?

Любая помощь будет оценена по достоинству.


person Alberto Montiel    schedule 10.07.2018    source источник
comment
Каков твой вопрос ?   -  person Bdloul    schedule 11.07.2018
comment
когда я пытаюсь вставить это в свой шаблон wordpress, у меня возникает ошибка ... сайт просто не работает ... не могли бы вы помочь мне обнаружить возможную ошибку?   -  person Alberto Montiel    schedule 11.07.2018


Ответы (1)


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

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

    ## Your Settings (below) ##

    $categories      = array(19);
    $targeted_states = array('FL');
    $base_rate       = 1;

    $user_state = WC()->customer->get_shipping_state();
    $user_state = empty($user_state) ? WC()->customer->get_billing_state() : $user_state;
    $surcharge  = 0; // Initializing

    // If user is not from florida we exit
    if ( ! in_array( $user_state, $targeted_states ) )
        return; // Exit

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item ) {
        if ( has_term( $categories, 'product_cat', $cart_item['product_id'] )  ){
            // calculating fee based on the defined rate and on item quatinty
            $surcharge += $cart_item['quantity'] * $base_rate;
        }
    }

    // Applying the surcharge
    if ( $surcharge > 0 ) {
        $cart->add_fee( __("State Tire Fee", "woocommerce"), $surcharge, true );
    }
}

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

person LoicTheAztec    schedule 11.07.2018
comment
Большое спасибо! работают отлично! Я использую этот код и надеюсь помочь кому-то другому ...! хорошего дня, мистер Лоик - person Alberto Montiel; 12.07.2018