在保存订单和发送 WooCommerce 电子邮件通知之前,将订单 ID 添加到订单项元数据

Add the order ID to the order item metadata before the order is saved and WooCommerce email notifications are sent

我需要在订单商品元数据中添加带有订单 ID 和密码的 link。

目前,我正在使用 woocommerce_checkout_create_order_line_item 操作成功地将其他信息添加到项目元数据中,但是当此操作为 运行 时,订单 ID 尚不可访问 (?)。

我可以用另一种方式执行此操作,以便在保存订单并向客户发送通知之前添加 link 吗?

add_action( 'woocommerce_checkout_create_order_line_item', 'custom_checkout_create_order_line_item', 20, 4 );
function custom_checkout_create_order_line_item( $item, $cart_item_key, $values, $order ) {
    if( ! isset( $values['test_title'] ) ) { return; }

    // add test info as order item metadata
    if( ! empty( $values['test_title'] ) ) {
        $test_pw = wp_generate_password(); // generate a password
        $item->update_meta_data( '_test_id', $values['test_id'] ); // add test id
        $item->update_meta_data( '_test_password', $test_pw ); // add test access password
        $item->update_meta_data( 'Access link', // add test access permalink
            get_permalink( $values['test_id'] ) . '?order=' . $order->get_id() . '&pw=' . $test_pw );
    }
}

您的挂钩在保存订单之前执行,并且在该 'save' 步骤中确定了订单 ID。

因此,除非您可以将此功能包含在您的挂钩中,否则我认为目前还没有办法知道订单 ID。

但是,根据您的问题,我了解到它涉及您希望在电子邮件中显示的项目元数据。因此,使用 woocommerce_order_item_meta_startwoocommerce_order_item_meta_end 挂钩是否可以让您在 wc_display_item_meta() WooCommerce 函数的输出之前或之后添加额外的产品信息:

function action_woocommerce_order_item_meta_start( $item_id, $item, $order, $plain_text ) {
    // On email notifications
    if ( ! is_wc_endpoint_url() && $item->is_type('line_item') ) {
        echo '<ul class="wc-item-meta"><li><strong class="wc-item-meta-label">Label</strong><p>Value order id = ' . $order->get_id() . '</p></li></ul>';
    }
}
add_action( 'woocommerce_order_item_meta_start', 'action_woocommerce_order_item_meta_start', 10, 4 );