我正在创建一个 WooCommerce 附加组件来自定义产品,基于访问者选择的选项,自定义价格也被计算并存储到 session 表中。
我也可以在购物车页面中获得该值。
我的问题:
我想更改产品的默认价格并将其替换为 WooCommerce 流程中的新计算值,如购物车、结帐、付款、邮件通知、订单...
有什么建议吗?
谢谢
最佳答案
让它工作的 Ce 右钩是 woocommerce_before_calculate_totals
。但是您必须完成(替换)代码才能在下面的 Hook 函数中获取新价格:
add_action( 'woocommerce_before_calculate_totals', 'custom_cart_items_prices', 10, 1 );
function custom_cart_items_prices( $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 ) {
// 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 = 500; // <== Add your code HERE
// Updated cart item price
$cart_item['data']->set_price( $new_price );
}
}
代码进入您活跃的子主题(或主题)的 function.php 文件或任何插件文件。
此代码已经过测试并适用于 WooCommerce 版本 3+。但是因为你没有提供任何代码,我无法测试它是否真的从 session 中获取新价格......
关于php - 更改 WooCommerce 购物车和结帐中的产品价格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44974645/