php - 仅在 WooCommerce Admin 单个订单中显示产品自定义字段
问题描述
此问题遵循如何在 WooCommerce 订单中显示产品自定义字段(自定义 SKU)回答我之前的问题。
如何使产品自定义字段articleid
(自定义 SKU)仅在每个订单项目的管理订单编辑页面中可见?
此外,它不适用于手动订单。如何在手动订单上也articleid
显示产品自定义字段(自定义 SKU)?
解决方案
更新了最后一个函数以避免与“订单项”的其他订单项目类型发生错误。
要使其仅在管理员上可见,在您的最后一个功能中,您需要将订单项元键从更改'articleid'
为'_articleid'
(在键的开头添加下划线),例如:
// Save as custom order item meta data and display on admin single orders
add_action( 'woocommerce_checkout_create_order_line_item', 'add_articleid_as_orders_item_meta', 10, 4 );
function add_articleid_as_orders_item_meta( $item, $cart_item_key, $values, $order ) {
$articleid = $values['data']->get_meta('articleid'); // Get product "articleid"
// For product variations when the "articleid" is not defined
if ( ! $articleid && $values['variation_id'] > 0 ) {
$product = wc_get_product( $values['product_id'] ); // Get the parent variable product
$articleid = $product->get_meta( 'articleid' ); // Get parent product "articleid"
}
if ( $articleid ) {
$item->add_meta_data( '_articleid', $articleid ); // add it as custom order item meta data
}
}
对于手动订单,您将使用以下内容:
add_action( 'woocommerce_before_save_order_item', 'action_before_save_order_item_callback' );
function action_before_save_order_item_callback( $item ) {
// Targeting only order item type "line_item"
if ( $item->get_type() !== 'line_item' )
return; // exit
$articleid = $item->get_meta('articleid');
if ( ! $articleid ) {
$product = $item->get_product(); // Get the WC_Product Object
// Get custom meta data from the product
$articleid = $product->get_meta('articleid');
// For product variations when the "articleid" is not defined
if ( ! $articleid && $item->get_variation_id() > 0 ) {
$product = wc_get_product( $item->get_product_id() ); // Get the parent variable product
$articleid = $product->get_meta( 'articleid' ); // Get parent product "articleid"
}
// Save it as custom order item (if defined for the product)
if ( $articleid ) {
$item->update_meta_data( '_articleid', $articleid );
}
}
}
代码位于活动子主题(或活动主题)的 functions.php 文件中。测试和工作。
与此线程相关:
推荐阅读
- linux - Ansible - 加载多个本地 yml 文件并合并它们的内容
- reactjs - React-Table:自定义 toggleAllRowsSelected 函数
- .net - 在 Blazor 网站上显示存储在私有 S3 存储桶中的图像
- amazon-web-services - Appflow upsert 错误:目标连接器中不存在 ID
- javascript - 如何记录 JSDoc 中的字符串参数必须匹配的模式?
- java - 如何在没有类或 id 的 selenium java 中与 span 交互?
- google-apps-script - 脚本在运行代码时未发送电子邮件
- assembly - 符号 = 在装配中
- javascript - 永久注册-PSFLoggingProvider | PSFramework 模块
- excel - 如何将超链接添加到引用使用 excel VBA 创建的演示文稿中的幻灯片的形状