将购物车元数据添加到 Woocommerce 中的管理订单屏幕?

Add cart metadata to admin order screen in Woocommerce?

我有一个隐藏的输入,我在 Woocommerce 产品屏幕上填充了一些 JS,我试图访问有关发送到管理屏幕和管理订单通知的订单元数据的信息,但我无法访问。

我觉得我可以将信息附加到购物车商品,但最终订单并没有这样做。

添加隐藏字段

function add_polarity_custom_hidden_field() {
    global $product;
    ob_start(); //Side note...not sure I need Output buffering here, feel free to let me know.
    
//Here's the input (value is populated with a separate radio group using JS)
?>

<input type="hidden" id="polarity-info" name="polarity_information" value=""> 

<?php
    $content = ob_get_contents();
    ob_end_flush();
    return $content;
}
add_action('woocommerce_after_variations_table', 'add_polarity_custom_hidden_field', 10);

我在下面使用这个函数将隐藏输入的值添加到购物车项目(不试图向客户显示此信息)

将自定义数据添加到购物车订单项:

/**
 * Add custom data to Cart
 */
function add_polarity_info_to_order($cart_item_data, $product_id, $variation_id) {
    if (isset($_REQUEST['polarity_information'])) {
        $cart_item_data['polarity_information'] = sanitize_text_field($_REQUEST['polarity_information']);
    }
    return $cart_item_data;
}

add_filter('woocommerce_add_cart_item_data', 'add_polarity_info_to_order', 10, 3);

在管理页面上显示为订单元数据:

我正在尝试让该信息显示在

  1. 作为项目元数据的订单通知电子邮件
  2. 管理行项目,也作为项目元数据

我试过像这样使用这个函数,但无法访问我正在寻找的属性:

add_action('woocommerce_admin_order_data_after_order_details', function ($order) {
    $order->get_ID();
    foreach ($order->get_items() as $item_id => $item) {
        $allmeta = $item->get_meta_data();
        var_dump($allmeta); //Not within these properties.
    }
});

旁注

我可以使用以下代码让商品显示在购物车页面上,但我无法将其转化为最终订单。

/**
 * Display information as Meta on Cart page
 */
function add_polarity_data_to_cart_page($item_data, $cart_item) {



    if (array_key_exists('polarity_information', $cart_item)) {
        $polarity_details = $cart_item['polarity_information'];

        $item_data[] = array(
            'key'   => 'Polarity Information',
            'value' => $polarity_details
        );
    }

    return $item_data;
}
add_filter('woocommerce_get_item_data', 'add_polarity_data_to_cart_page', 10, 2);

您必须使用 woocommerce_checkout_create_order_line_item 挂钩将购物车数据存储为订单项元数据。

所以:

add_action('woocommerce_checkout_create_order_line_item', 'save_custom_order_item_meta_data', 10, 4 );
function save_custom_order_item_meta_data( $item, $cart_item_key, $values, $order ) {

    if ( isset( $values['polarity_information'] ) ) {
        $item->update_meta_data( '_polarity_information', $values['polarity_information'] );
    }

}

您现在可以从 woocommerce_admin_order_data_after_order_details 挂钩访问订单项元数据。

代码已经过测试和运行。将其添加到您的活动主题 functions.php.

相关答案