php - 在 WooCommerce 管理订单项目上显示产品自定义字段也适用于可变产品
问题描述
基于在 WooCommerce 答案代码中的订单编辑页面上显示自定义字段,我做了一些细微的更改:
add_action( 'woocommerce_before_order_itemmeta', 'add_admin_order_item_custom_fields', 10, 2 );
function add_admin_order_item_custom_fields( $item_id, $item ) {
// Targeting line items type only
if( $item->get_type() !== 'line_item' ) return;
$product = $item-> get_product();
$value1 = $product->get_meta('model_number');
if ( ! empty($value1) ) {
echo '<table cellspacing="0" class="display_meta">';
if ( ! empty($value1) ) {
echo '<tr><th>' . __("Modelnummer", "woocommerce") . ':</th><td>' . $value1 . '</td></tr>';
}
echo '</table>';
}
}
我想让该代码也适用于可变产品自定义字段。
我需要进行哪些更改才能使其适用于可变产品?
解决方案
如果它是没有为其设置自定义字段的产品变体,则以下将获取父变量产品自定义字段:
add_action( 'woocommerce_before_order_itemmeta', 'add_admin_order_item_custom_fields', 10, 2 );
function add_admin_order_item_custom_fields( $item_id, $item ) {
// Targeting line items type only
if( $item->get_type() !== 'line_item' ) return;
$product = $item->get_product();
$model_number = $product->get_meta('model_number');
// Get the parent variable product custom field if empty value
if( $item->get_variation_id() > 0 && empty($model_number) ) {
$parent_product = wc_get_product( $item->get_product_id() );
$model_number = $parent_product->get_meta('model_number');
}
if ( ! empty($model_number) ) {
echo '<table cellspacing="0" class="display_meta"><tr>
<th>' . __("Model number", "woocommerce") . ': </th>
<td>' . $model_number . '</td>
</tr></table>';
}
}
代码位于活动子主题(或活动主题)的 functions.php 文件中。测试和工作。
推荐阅读
- php - Ad_group_ad_asset_view 中的 Google 广告 api 字段asset.name 为空,类型为 YOUTUBE_VIDEO
- symfony - 始终在学说 DQL 中获得列
- reactjs - 没有重载与 Vega-react 库匹配此调用
- encoding - 如何为 psexec 执行 UAC?
- python - 引发特定异常python
- python - 信息 - 任务退出并返回代码 Negsignal.SIGSEGV
- python - 带有关联表类对象的 Flask SQLAlchemy 多对多
- java - JAVA Json:属性的getter定义冲突
- perl - Perl - 子程序“Hash::Merge::merge”的深度递归
- mysql - 交叉连接 2 个表,但包含一个空行