在WooCommerce中,我使用下面的钩子功能来改变购物车中产品的价格。
add_action('woocommerce_before_calculate_totals', 'set_custom_price',1000,1);
function set_custom_price($cart_obj) {
foreach ($cart_obj->get_cart() as $key => $value) {
if($value['alredy_have_number'] == true) {
$value['data']->set_price(0.90);
}
}
}
我想改变订阅产品的注册费,但是对于经常性的价格来说,它的工作效果很好,我可以使用什么函数或钩子来实现?
要改变 一些购物车项目的具体元数据 喜欢 注册费,您将使用 WC_Data
办法 update_meta_data()
可用于任何 WC_Product
对象如订阅产品。
相关的 注册费 meta_key
要用的是 _subscription_sign_up_fee
所以在你的钩子函数代码中,你将用这种方式来改变它的价格。
add_action( 'woocommerce_before_calculate_totals', 'change_subscription_data', 1000, 1 );
function change_subscription_data( $cart ) {
if (is_admin() && !defined('DOING_AJAX'))
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item ) {
// Check that product custom cart item data "alredy_have_number" exist and is true
if( isset($cart_item['alredy_have_number']) && $cart_item['alredy_have_number'] ) {
// Change subscription price
$cart_item['data']->set_price(10.60);
// Only for subscription products
if ( in_array( $cart_item['data']->get_type(), ['subscription', 'subscription_variation']) ) {
// Change subscription Sign up fee
$cart_item['data']->update_meta_data('_subscription_sign_up_fee', 3.40);
}
}
}
}
代码在你的活动子主题(或活动主题)的function.php文件中。经过测试,工作。