首页 > 解决方案 > 在 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>';
    }
}

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

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

标签: phpwordpresswoocommercecustom-fieldsorders

解决方案


如果它是没有为其设置自定义字段的产品变体,则以下将获取父变量产品自定义字段:

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 文件中。测试和工作。


推荐阅读