更新时间:2023-10-25 14:50:10
已使用 get_price()
方法更新了……
Updated with get_price()
method …
此自定义挂钩函数中应使用 woocommerce_before_calculate_totals
动作挂钩设置,您的产品ID或产品ID的数组。
然后,您可以为每个商品进行自定义计算,以设置自定义价格,该价格将在购物车,结帐时以及在提交订单后进行设置。
You should use woocommerce_before_calculate_totals
action hook setting inside this custom hooked function, your products IDs or an array of product IDs.
Then for each of them you can make a custom calculation to set a custom price that will be set on Cart, checkout and after submitting in the order.
此处是在WooCommerce 3.0+版上测试过的功能代码:
Here is that functional code tested on WooCommerce version 3.0+:
add_action( 'woocommerce_before_calculate_totals', 'adding_custom_price', 10, 1);
function adding_custom_price( $cart_obj ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// Set below your targeted individual products IDs or arrays of product IDs
$target_product_id = 53;
$target_product_ids_arr = array(22, 56, 81);
foreach ( $cart_obj->get_cart() as $cart_item ) {
// The corresponding product ID
$product_id = $cart_item['product_id'];
// For a single product ID
if($product_id == $target_product_id){
// Custom calculation
$price = $cart_item['data']->get_price() + 50;
$cart_item['data']->set_price( floatval($price) );
}
// For an array of product IDs
elseif( in_array( $product_id, $target_product_ids_arr ) ){
// Custom calculation
$price = $cart_item['data']->get_price() + 30;
$cart_item['data']->set_price( floatval($price) );
}
}
}
代码已输入您的活动子主题(或主题)或任何插件文件中的function.php文件。
然后,您可以轻松地就像在代码中一样,用get_post_meta()函数将我的虚假计算中的固定值替换为产品动态值,就像在代码中那样
$ product_id
每个购物车商品…
Then you can easily replace the fixed values in my fake calculations by your product dynamic values with that with get_post_meta() function just like in your code as you have the
$product_id
for each cart item…