使用 WC Kalkulator 产品字段值更新 WooCommerce 购物车项目属性

问题描述 投票:0回答:1

在 WooCommerce 中,我使用 WC Kalkulator 插件来创建一个简单的产品 (ID 4692)。问题是,这个简单的产品只有静态重量和尺寸值,这些值被拉入每个购物车项目添加中。这使得重量为 2 磅的 12"x12" 标志板的运输成本与重量为 80 磅的 120" x 48" 标志板的运输成本相同。我在 WC Kalkulator 插件中设置了字段来定义计算的重量和尺寸。

我启动了一个代码,旨在使用计算出的数据应用于输入购物车时的产品数据。购物车项目的每个实例对于输入的值都应该是唯一的。

我会说我不是编码员,我在 Copilot AI 的帮助下走到了这一步:

add_action( 'woocommerce_before_calculate_totals', 'update_custom_price', 10, 1 );
function update_custom_price( $cart_object ) {
    foreach ( $cart_object->get_cart() as $cart_item ) {
        // Get the WC_Product object
        $product = $cart_item['data'];
        $product_id = $product->get_id();

        // Check if the product ID matches the specific product
        if ( $product_id == 4692 ) {
            // Get the custom field value
            $custom_field_value = get_post_meta( 4692, 'wck_weight', true );
            $custom_field_value1 = get_post_meta( 4692, 'wck_length', true );
            $custom_field_value2 = get_post_meta( 4692, 'wck_width', true );
            $custom_field_value3 = get_post_meta( 4692, 'wck_height', true );

            // Update the product weight and dimensions
            $product->set_weight( $custom_field_value );
            $product->set_length( $custom_field_value1 );
            $product->set_width( $custom_field_value2 );
            $product->set_height( $custom_field_value3 );
        }
    }
}

我不知道“get_post_meta”是否在正确的位置查找 WCK 字段。这些字段的命名正确,产品 ID 符合我的意图。

php woocommerce crud cart custom-fields
1个回答
0
投票

您的代码中存在一些错误,因为数据作为自定义购物车项目数据发布,但没有相关的产品元数据。尝试以下操作:

add_action( 'woocommerce_before_calculate_totals', 'custom_item_weight_and_dimensions' );
function custom_item_weight_and_dimensions( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Loop through cart items
    foreach ( $cart->get_cart() as $item ) {
        if ( isset($item['wckalkulator_fields']) ) {
            $fields = (array) $item['wckalkulator_fields'];
            if ( isset($fields['wck_weight']) && !empty($fields['wck_weight']) ) {
                $item['data']->set_weight($fields['wck_weight']);
            }

            if ( isset($fields['wck_length']) && !empty($fields['wck_length']) ) {
                $item['data']->set_length($fields['wck_length']);
            }

            if ( isset($fields['wck_width']) && !empty($fields['wck_width']) ) {
                $item['data']->set_width($fields['wck_width']);
            }

            if ( isset($fields['wck_height']) && !empty($fields['wck_height']) ) {
                $item['data']->set_height($fields['wck_height']);
            }
        }
    }
}

代码位于子主题的 function.php 文件中(或插件中)。如果您在代码尝试中给出了正确的字段键,它应该可以工作。

请注意,在我的代码尝试中,无需定义产品 ID,因为我的代码将检查每个相关的自定义购物车项目数据是否存在并具有值,以更新相关的购物车项目(产品)属性。

© www.soinside.com 2019 - 2024. All rights reserved.