首页 > 解决方案 > 在 WooCommerce 订单和电子邮件中保存并显示产品自定义元数据

问题描述

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

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

单个产品页面参考图片

然后我们设法使用 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;
}

购物车页面中项目元数据中的自定义字段

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

请帮忙!!

标签: phpwordpresswoocommerceordersemail-notifications

解决方案


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

// 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 文件中。测试和工作。


推荐阅读