Добавьте дополнительную цену к цене продукта на основе количества товаров в Woocommerce - PullRequest
0 голосов
/ 04 декабря 2018

Основываясь на ценах изменения Woocommerce для определенной страны , я пытаюсь добавить к цене продукта дополнительную стоимость, которая должна быть разделена на количество элементов корзины.

add_filter('woocommerce_get_price', 'return_custom_price', $product, 2);

function return_custom_price($price, $product) {    
    global $post, $woocommerce;
    // Array containing country codes
    $container = 3000;
    $county = array('GR');
    // Get the post id 
    $post_id = $post->ID;

    $cart_tot = $woocommerce->cart->cart_contents_count;
    // Amount to increase by
    $amount = ($container / $cart_tot);
    // If the customers shipping country is in the array and the post id matches
    if ( in_array( $woocommerce->customer->get_shipping_country(), $county ) && ( $post_id == '1151' || $post_id == '1152' ) ){
        // Return the price plus the $amount
       return $new_price = $price + $amount;
    } else {
        // Otherwise just return the normal price
        return $price;
    }
} 

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

Когда я использовал echo $ woocommerce-> cart-> cart_contents_count;он показывает количество товаров в корзине, но несколько раз подряд.…

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

1 Ответ

0 голосов
/ 05 декабря 2018

Начиная с Woocommerce 3, хук woocommerce_get_price устарел и заменен.Кроме того, код действительно устарел, полон ошибок и ошибок.

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

В любом случае, вот ваш повторный код, , но вы не должны его использовать (см. Другой способ ниже) :

add_filter( 'woocommerce_product_get_price', 'custom_specific_product_prices', 10, 2 );
function custom_specific_product_prices( $price, $product ) {
    // Exit when cart is empty
    if( WC()->cart->is_empty() )
        return $price; // Exit

    ## ----- Your settings below ----- ##

    $countries   = array('GR'); // Country codes
    $product_ids = array('1151', '1152'); // Product Ids
    $container   = 3000; // Container cost

    ## ------------------------------- ##

    if( ! in_array( $product->get_id(), $product_ids ) )
        return $price; // Exit

    $cart_items_count = WC()->cart->get_cart_contents_count();
    $shipping_country = WC()->customer->get_shipping_country();

    // If the customers shipping country is in the array and the post id matches
    if ( in_array( $shipping_country, $countries ) ) {
        // Return the price plus the $amount
        $price +=  $container / $cart_items_count;
    }

    return $price;
}

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


Что вы можете сделать, это добавить плату "Контейнер":

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

    ## ----- Your settings below ----- ##

    $countries   = array('GR'); // Country codes
    $product_ids = array('1151', '1152'); // Product Ids
    $container   = 3000; // Container cost

    ## ------------------------------- ##

    $shipping_country = WC()->customer->get_shipping_country();
    $items_found      = false;

    if ( ! in_array( $shipping_country, $countries ) )
        return; // Exit

    foreach( $cart->get_cart() as $cart_item ) {
        if ( array_intersect( array( $cart_item['variation_id'], $cart_item['product_id'] ), $product_ids ) )
            $items_found = true; // Found
    }

    if ( $items_found )
        $cart->add_fee( __('Container fee'), $container );
}

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

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