在 WooCommerce 购物车和结帐中更改产品价格

Thi*_*mar 4 php wordpress cart woocommerce price

我正在创建一个 WooCommerce 插件来自定义产品,基于访问者选择的选项,自定义价格也被计算并存储到会话表中。
我也可以在购物车页面中获得该值。

我的问题:
我想更改产品的默认价格并将其替换为 WooCommerce 流程中的新计算值,如购物车、结帐、付款、邮件通知、订单...

请问有什么建议吗?

谢谢

Loi*_*tec 5

让它工作的右勾是woocommerce_before_calculate_totals. 但是您必须完成(替换)代码才能在下面的挂钩函数中获取新价格:

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 ); 
    }
}
Run Code Online (Sandbox Code Playgroud)

代码位于活动子主题(或主题)的 function.php 文件或任何插件文件中。

此代码经过测试并适用于 WooCommerce 版本 3+。但是由于您没有提供任何代码,因此我无法对其进行测试以真正从会话中获取新价格......