php - 在 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;
}
我们现在的问题是,我们需要将此发货延迟通知添加到电子邮件中(分别显示在包含此数据的每个项目下方)以及订单页面上。那怎么可能呢?由于我已经检查了一堆线程,但所有线程都是使用动态字段(用户在购买时完成的)完成的,但我们的案例场景完全不同。
请帮忙!!
解决方案
以下会将您的自定义字段保存为订单项元数据并在任何地方显示:
// 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 文件中。测试和工作。
推荐阅读
- xml - 是否可以从 Mac OS 使用 XSD 工具?
- python - 为什么 Python 的交互式解释器有时会输出转义字符?
- c# - C# - 将 Switch 语句转换为 If-Else
- amazon-web-services - 尝试从 aws cli 更新 AWS stepfunction 时出现 JSON 解析错误
- mysql - 左连接返回多行而不是一行
- .htaccess - 添加过期标头 - gtmetrix
- angular - 如何将 MatButton 添加到 Angular 库中(Angular 9)
- dji-sdk - 使用 DJI OSDK 时代码不执行我的主要功能
- octobercms - 十月 CMS 属于ToMany/hasMany 与自我的关系
- javascript - 从另一个数组中获取所有相同元素的最快方法