且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

更改WooCommerce购物车中产品的价格并结帐

更新时间:2023-10-25 14:54:16

Ce使其正常运行的正确方法是 woocommerce_before_calculate_totals 。但是您必须完成(替换)代码才能在下面的挂钩函数中获得新价格:

Ce right hook to get it working is woocommerce_before_calculate_totals. But you will have to complete (replace) the code to get the new price in the hooked function below:

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文件中主题(或主题)或任何插件文件中。

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

此代码已经过测试,可在WooCommerce 3+版本上运行。但是,由于您不提供任何代码,因此我无法对其进行测试以真正从会话中获取新价格…

This code is tested and works on WooCommerce versions 3+. But as you don't give any code I can't test it for real getting the new price from session…