基于Woocommerce change prices for a certain country,我试图在产品价格上增加一笔额外费用,该费用必须除以购物车数量。
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;时,它显示购物车项目计数,但连续显示多次。…
感谢您的帮助。
答案 0 :(得分:0)
自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文件中。经过测试,可以正常工作。