且构网

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

动态购物车项目定价不适用于 WooCommerce 3.0+ 中的订单

更新时间:2023-10-25 14:49:46

更新为 get_price() 方法……

Updated with get_price() method …

您应该在此自定义挂钩函数、您的产品 ID 或产品 ID 数组中使用 woocommerce_before_calculate_totals 操作挂钩设置.
然后,您可以为每个人进行自定义计算以设置将在购物车、结帐和提交订单后设置的自定义价格.

You should use woocommerce_before_calculate_totals action hook setting inside this custom hooked function, your products IDs or an array of product IDs.
Then for each of them you can make a custom calculation to set a custom price that will be set on Cart, checkout and after submitting in the order.

这是在 WooCommerce 3.0+ 版上测试的功能代码:

Here is that functional code tested on WooCommerce version 3.0+:

add_action( 'woocommerce_before_calculate_totals', 'adding_custom_price', 10, 1);
function adding_custom_price( $cart_obj ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Set below your targeted individual products IDs or arrays of product IDs
    $target_product_id = 53;
    $target_product_ids_arr = array(22, 56, 81);

    foreach ( $cart_obj->get_cart() as  $cart_item ) {
        // The corresponding product ID
        $product_id = $cart_item['product_id'];

        // For a single product ID
        if($product_id == $target_product_id){
            // Custom calculation
            $price = $cart_item['data']->get_price() + 50;
            $cart_item['data']->set_price( floatval($price) );
        } 

        // For an array of product IDs 
        elseif( in_array( $product_id, $target_product_ids_arr ) ){
            // Custom calculation
            $price = $cart_item['data']->get_price() + 30;
            $cart_item['data']->set_price( floatval($price) );
        }
    }
}

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

然后,您可以使用 get_post_meta() 函数轻松地将我的虚假计算中的固定值替换为您的产品动态值,就像在您的代码中一样,因为您拥有 $product_id强>对于每个购物车项目......

Then you can easily replace the fixed values in my fake calculations by your product dynamic values with that with get_post_meta() function just like in your code as you have the $product_id for each cart item…