在 WooCommerce 订单和电子邮件中保存和显示产品自定义元数据

Save and display product custom meta on WooCommerce orders and emails

好的,基本上我们在 WooCommerce 商店中使用 ACF 创建了一个自定义字段,以便为特定产品添加“发货延迟”通知。

这是我们取得的成果的演示:https://www.safe-company.com/shop/machines/uvc-disinfection-lamp/

Single Product Page Reference Image

然后我们设法使用 Elementor(页面构建器)将此通知放在单个产品页面中,然后将此信息添加到购物车和结帐页面中的项目数据,并将以下代码添加到我们的 functions.php

// Render the custom product field in cart and checkout
add_filter( 'woocommerce_get_item_data', 'wc_add_shipping_delay', 10, 2 );
function wc_add_shipping_delay( $cart_data, $cart_item ) 
{
    $custom_items = array();

    if( !empty( $cart_data ) )
        $custom_items = $cart_data;

    // Get the product ID
    $product_id = $cart_item['product_id'];

    if( $custom_field_value = get_post_meta( $product_id, 'shipping_delay_for_out_of_stock_items', true ) )
        $custom_items[] = array(
            'name'      => __( 'Shipping Delay', 'woocommerce' ),
            'value'     => $custom_field_value,
            'display'   => $custom_field_value,
        );

    return $custom_items;
}

Custom Field in Item Meta from Cart Page

我们现在的问题是我们需要将此发货延迟通知添加到电子邮件(分别显示在包含此数据的每个项目下方)以及订单页面上。那怎么可能呢?由于我已经检查了一堆线程,但所有线程都是使用动态字段完成的(用户在购买时完成),但我们的案例场景完全不同。

请帮忙!!

以下会将您的自定义字段保存为订单项元数据并在各处显示:

// Save and display "shipping delay" on order items everywhere
add_filter( 'woocommerce_checkout_create_order_line_item', 'action_wc_checkout_create_order_line_item', 10, 4 );
function action_wc_checkout_create_order_line_item( $item, $cart_item_key, $values, $order ) {

    // Get the shipping delay
    $value = $values['data']->get_meta( 'shipping_delay_for_out_of_stock_items' );

    if( ! empty( $value ) ) {
        // Save it and display it
        $item->update_meta_data( __( 'Shipping Delay', 'woocommerce' ), $value );
    }
}   

代码进入您的活动子主题(或活动主题)的 functions.php 文件。已测试并有效。