Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display custom order item metadata only on WooCommerce admin orders

To display custom data , I use this hook 'woocommerce_checkout_create_order_line_item'. He works good. But it displays data in three places - in the admin panel (in order), in the order details and in the personal account. I need the data to be displayed only in the admin panel. how to do it? My code

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

enter image description here

like image 204
Anya Moroz Avatar asked Nov 06 '25 14:11

Anya Moroz


1 Answers

Use the following to display a custom download button on admin order items only (code is commented):

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

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

The custom download button is only displayed in admin order items.

enter image description here

like image 196
LoicTheAztec Avatar answered Nov 08 '25 05:11

LoicTheAztec