首页 > 解决方案 > 仅在 WooCommerce 管理员订单上显示自定义订单项目元数据

问题描述

为了显示自定义数据,我使用了这个钩子“woocommerce_checkout_create_order_line_item”。他工作得很好。但它会在三个地方显示数据 - 管理面板(按顺序)、订单详细信息和个人帐户。我需要仅在管理面板中显示数据。怎么做?我的代码

 add_action( 'woocommerce_checkout_create_order_line_item', 'wdm_add_custom_order_line_item_meta', 10, 4 );

function wdm_add_custom_order_line_item_meta( $item, $cart_item_key, $values, $order )
{
    if ( array_key_exists( 'file', $values ) ) {
        $product_id = $item->get_product_id();
        $permfile = $values['file'];
        $basePath = plugin_base_url();
        $fileid = $permfile;
        ....
        $item->add_meta_data('File','<button >  <a href="'.$fileid.'" download>' . Download.   '</a></button>');
    }
}

在此处输入图像描述

标签: phpwordpresswoocommercebackendorders

解决方案


使用以下内容仅在管理订单项目上显示自定义下载按钮(代码已注释)

// Save custom order item meta
add_action( 'woocommerce_checkout_create_order_line_item', 'save_custom_order_item_meta', 10, 4 );
function save_custom_order_item_meta( $item, $cart_item_key, $values, $order ) {
    if ( isset($values['file']) && ! empty($values['file']) ) {
        // Save it in an array to hide meta data from admin order items
        $item->add_meta_data('file', array( $values['file'] ) );
    }
}

// Get custom order item meta and display a linked download button
add_action( 'woocommerce_after_order_itemmeta', 'display_admin_order_item_custom_button', 10, 3 );
function display_admin_order_item_custom_button( $item_id, $item, $product ){
    // Only "line" items and backend order pages
    if( ! ( is_admin() && $item->is_type('line_item') ) )
        return;

    $file_url = $item->get_meta('file'); // Get custom item meta data (array)

    if( ! empty($file_url) ) {
        // Display a custom download button using custom meta for the link
        echo '<a href="' . reset($file_url) . '" class="button download" download>' . __("Download", "woocommerce") . '</a>';
    }
}

代码位于活动子主题(或活动主题)的 functions.php 文件中。测试和工作。

自定义下载按钮仅显示在管理订单项目中。

在此处输入图像描述


推荐阅读