[英]Add an extra cost to product price based on cart item count in Woocommerce
根据某个国家/地区的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;时, 它显示购物车项目计数,但连续显示多次。…
任何帮助表示赞赏。
从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文件中。 经过测试和工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.