处理后在订单中显示产品自定义字段值

Displaying product custom fields values in the order once processed

在 woocommerce 上,我使用下面的代码在购物车和结账时呈现一些产品自定义字段:

add_filter( 'woocommerce_get_item_data', 'rendering_meta_field_on_cart_and_checkout', 10, 2 );

function rendering_meta_field_on_cart_and_checkout( $cart_data, $cart_item ) {
    $custom_items = array();

    if( !empty( $cart_data ) ) {
        $custom_items = $cart_data;
    }
    if( isset( $cart_item['wccpf_enter_product_id'] ) ) {

        $diamond = $cart_item['wccpf_enter_product_id'];

        $pacolor = get_the_terms($diamond, 'pa_color');
        foreach ( $pacolor  as $pacolor  ) {
           $color= $pacolor ->name;
        }


        $custom_items[] = array( "name" => "color", "value" => $color);
    }
    return $custom_items;
}

如何在订单中显示自定义产品字段 wccpf_enter_product_id 的值?

谢谢。

您可以使用挂钩在 woocommerce_add_order_item_meta 动作挂钩中的自定义函数来实现此目的。

You will need first to add an attribute in your products to get a "readable clean label" for your custom field value that is going to appear as order items meta data.

For that you have to create an attribute first and then set it in your product with any value (as you will replace this value in the code below).

See HERE some more explanations about that process…

You will have to replace in my code the 'custom_field_key' by your specific custom key that you will find on wp_woocommerce_order_itemmeta MySQL table for the corresponding item ID for your specific Order ID.
To find the corresponding item ID for the order, you can search in wp_woocommerce_order_items MySQL table with the Order ID…

You will have also to set your correct attribute slug instead of 'pa_your_attribute' to display in your orders the correct label text for this custom field value.
(see below other similar answers references).

所以你的代码将是这样的:

// ADD THE INFORMATION AS META DATA SO THAT IT CAN BE SEEN AS PART OF THE ORDER
add_action('woocommerce_add_order_item_meta','add_and_update_values_to_order_item_meta', 1, 3 );
function add_and_update_values_to_order_item_meta( $item_id, $item_values, $item_key ) {

    // Getting your custom product ID value from order item meta
    $custom_value = wc_get_order_item_meta( $item_id, 'custom_field_key', true );

    // Here you update the attribute value set in your simple product
    wc_update_order_item_meta( $item_id, 'pa_your_attribute', $custom_value );
    }
}

代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件。

这应该有效


相关回答:

  • Adding user custom field value to order items details

  • Displaying custom product data in Order items view