Chris Hawkins
Chris Hawkins

Reputation: 451

Add custom order item meta data

I am currently working on some code that will run with the woocommerce_order_status_completed hook. The code will connect to a 3rd party to retrieve a serial number for the purchased item. Originally I was planning on just emailing the serial to the customer, but I was wondering, would it be possible to add the retrieved serial number to the ordered item (meta?) so that when the customer goes to their account page to view the order, they see the serial number listed there (under the product(s) that was purchased?

Is this possible some how? Add information to the order to be shown in the account page?

Upvotes: 5

Views: 26241

Answers (2)

Ari Abimanyu
Ari Abimanyu

Reputation: 91

If you are using a class:

add_action( 'woocommerce_add_order_item_meta', array( $this,'add_order_item_meta'), 10, 2 );

public static function add_order_item_meta($item_id, $values) {
    $key = 'statusitem'; // Define your key here
    $value = 'AAA'; // Get your value here

    wc_update_order_item_meta($item_id, $key, $value);
}

If you're not using a class:

add_action( 'woocommerce_add_order_item_meta', 'add_order_item_meta', 10, 2 );

function add_order_item_meta($item_id, $values) {
    $key = 'statusitem'; // Define your key here
    $value = 'AAA'; // Get your value here

    wc_update_order_item_meta($item_id, $key, $value);
}

The JSON response call from API; look at meta_data:

"line_items": [{
    "id": 425,
    "name": "FANTA",
    "product_id": 80,
    "variation_id": 0,
    "quantity": 1,
    "tax_class": "",
    "subtotal": "30000.00",
    "subtotal_tax": "0.00",
    "total": "30000.00",
    "total_tax": "0.00",
    "taxes": [],
    "meta_data": [{
        "id": 3079,
        "key": "statusitem",
        "value": "AAA"
    }],
    "sku": "000000000000009",
    "price": 30000
}],

Upvotes: 4

José
José

Reputation: 239

Sure, add it like this:

function add_order_item_meta($item_id, $values) {
    $key = ''; // Define your key here
    $value = ''; // Get your value here
    woocommerce_add_order_item_meta($item_id, $key, $value);
}
add_action('woocommerce_add_order_item_meta', 'add_order_item_meta', 10, 2);

Upvotes: 8

Related Questions