Php 在WooCommerce管理订单项目上显示产品自定义字段,也用于可变产品
根据答案代码,我做了一些小改动:Php 在WooCommerce管理订单项目上显示产品自定义字段,也用于可变产品,php,wordpress,woocommerce,custom-fields,orders,Php,Wordpress,Woocommerce,Custom Fields,Orders,根据答案代码,我做了一些小改动: 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() !== '
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);
函数添加\管理\订单\项目\自定义\字段($item\u id,$item){
//仅针对行项目类型
如果($item->get_type()!='line_item')返回;
$product=$item->get_product();
$value1=$product->get_meta('model_number');
如果(!空($value1)){
回声';
如果(!空($value1)){
回音“.”Modelnummer“,”woocommerce“:“.$value1.”;
}
回声';
}
}
我想使该代码也适用于可变产品自定义字段
要使其适用于可变产品,我需要更改哪些内容?如果是未设置自定义字段的产品变体,则以下内容将获得父变量产品自定义字段:
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>';
}
}
add_action('woocommerce_-before_-order_-itemmeta','add_-admin_-order_-item_-custom_-fields',10,2);
函数添加\管理\订单\项目\自定义\字段($item\u id,$item){
//仅针对行项目类型
如果($item->get_type()!='line_item')返回;
$product=$item->get_product();
$model_number=$product->get_meta('model_number');
//如果值为空,则获取父变量产品自定义字段
如果($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');
}
如果(!空($model_number)){
回声'
“.”(“型号”,“woocommerce”):
“.$model_number”
';
}
}
代码进入活动子主题(或活动主题)的functions.php文件。测试并运行。@eqr21刚刚更新了代码…测试并运行。请对此答案提供一些反馈,我们将不胜感激。实施后,即使对于礼品卡等定制变体类型,它似乎也能正常工作。:)谢谢。@eqr21是的,这适用于所有产品类型