我正在使用 WooCommerce 3.0+,并且我已在某个页面上设置了产品价格。
$regular_price = get_post_meta( $_product->id, '_regular_price', true);
$buyback_percentage = get_post_meta( $_product->id, '_goldpricelive_buy_back', true);
$fixed_amount = get_post_meta( $_product->id, '_goldpricelive_fixed_amount', true);
$markedup_price = get_post_meta( $_product->id, '_goldpricelive_markup', true);
$buyback_price = ($regular_price - $fixed_amount)/(1 + $markedup_price/100) * (1-$buyback_percentage/100);
$_product->set_price($buyback_price);
我的购物车上的价格正在更新,但是当我点击提交订单时,订单对象似乎没有获取我设置的价格。需要原产地价格。
有什么办法可以实现这个目标吗?
谢谢
使用
get_price()
方法更新...
您应该在此自定义挂钩函数、您的产品 ID 或产品 ID 数组中使用
woocommerce_before_calculate_totals
操作挂钩设置。 这是在 WooCommerce 版本 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