Home > Software engineering >  Add the order ID to the order item metadata before the order is saved and WooCommerce email notifica
Add the order ID to the order item metadata before the order is saved and WooCommerce email notifica

Time:11-27

I need to add a link with the order ID and a password to the order item metadata.

Currently, I am adding successfully other info to the item metadata with the woocommerce_checkout_create_order_line_item action, but when this action is running the order ID is not accessible yet (?).

Can I do this in another way, so the link will be added before the order is saved and a notification to the customer is sent?

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

CodePudding user response:

Your hook is executed before the order is saved, and in that 'save' step the order id is determined.

So unless you could include this functionality in your hook I don't believe there is a way to know the order id at that point already.

However, from your question I understand that it concerns item meta data that you want to display in e-mails. So isn't it an option to use the woocommerce_order_item_meta_start or the woocommerce_order_item_meta_end hook that allows you to add additional product information before or after the output from the wc_display_item_meta() WooCommerce function:

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 ><li><strong >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 );
  • Related