在WooCommerce管理员订购商品上也显示商品自定义字段,也用于可变商品 [英] Display product custom fields on WooCommerce Admin Order Items also for variable products

查看:68
本文介绍了在WooCommerce管理员订购商品上也显示商品自定义字段,也用于可变商品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于显示自定义字段在WooCommerce的订单编辑页面上回答代码,我做了一些细微更改:

Based on Show custom fields on the order editing page in WooCommerce answer code where I did some slight changes:

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>';
    }
}

我也想使该代码也适用于可变产品自定义字段.

I would like to make that code works for variable products custom fields too.

要使其适用于可变产品,我需要进行哪些更改?

What do I need to change to make it work for variable products?

推荐答案

如果它是未设置自定义字段的产品变体,则以下内容将获得父变量产品自定义字段:

The following will get the parent variable product custom field if it is a product variation with no custom field set for it:

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文件中.经过测试,可以正常工作.

Code goes in functions.php file of the active child theme (or active theme). Tested and works.

这篇关于在WooCommerce管理员订购商品上也显示商品自定义字段,也用于可变商品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆