在Woocommerce中将购物车项目的价格替换为自定义字段值 [英] Replace the price of the cart item with a custom field value in Woocommerce
本文介绍了在Woocommerce中将购物车项目的价格替换为自定义字段值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在WooCommerce中,我试图用自定义字段价格替换购物车项目的价格.
In WooCommerce I am trying to replace the price of the cart items inwith a custom field price.
这是我的代码:
function custom_cart_items_price ( $cart_object ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
foreach ( $cart_object->get_cart() as $cart_item ) {
// get the product id (or the variation id)
$id = $cart_item['data']->get_id();
// GET THE NEW PRICE (code to be replace by yours)
$new_price = (int)get_post_meta( get_the_ID(), '_c_price_field', true ); // <== Add your code HERE
// Updated cart item price
$cart_item['data']->set_price( $new_price );
}
}
add_filter( 'woocommerce_before_calculate_totals', 'custom_cart_items_price');
但是它不起作用.我在做什么错了?
But it doesn't work. What I am doing wrong?
任何帮助将不胜感激.
推荐答案
如果在购物车中将 get_the_ID()
与 get_post_meta()
一起使用,则此方法无效.您应该改用:
It doesn't work if you use get_the_ID()
with get_post_meta()
in cart. You should use instead:
add_action( 'woocommerce_before_calculate_totals', 'custom_cart_items_price');
function custom_cart_items_price ( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
foreach ( $cart->get_cart() as $cart_item ) {
// get the product id (or the variation id)
$product_id = $cart_item['data']->get_id();
// GET THE NEW PRICE (code to be replace by yours)
$new_price = get_post_meta( $product_id, '_c_price_field', true );
// Updated cart item price
$cart_item['data']->set_price( floatval( $new_price ) );
}
}
代码进入您的活动子主题(或活动主题)的function.php文件中.
现在应该可以了
这篇关于在Woocommerce中将购物车项目的价格替换为自定义字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文