I want to save order item category in order item meta. Got help from this answer https://stackoverflow.com/a/55575047/12183966 but i am getting an Internal Server Error on WooCommerce checkout.
Uncaught Error: Call to a member function get_items() on null
I can't figure out what i am doing wrong here. Any advice?
This is my code:
// Save item custom fields label and value as order item meta data
add_action('woocommerce_add_order_item_meta','save_in_order_item_meta', 10, 3 );
function save_in_order_item_meta( $item_id, $values, $cart_item_key ) {
foreach ($order->get_items() as $item ) {
$term_names = wp_get_post_terms( $item->get_product_id(), 'product_cat', ['fields' => 'names'] );
// Output as a coma separated string
$cat = implode(', ', $term_names);
wc_add_order_item_meta( $item_id, 'category', $cat );
}
}
CodePudding user response:
woocommerce_add_order_item_meta
hook is deprecated since WooCommerce 3. Usewoocommerce_checkout_create_order_line_item
instead$order
is undefined in your code attempt
So you get:
function action_woocommerce_checkout_create_order_line_item( $item, $cart_item_key, $values, $order ) {
// Get the product categories for this item
$term_names = wp_get_post_terms( $item->get_product_id(), 'product_cat', array( 'fields' => 'names' ) );
// Output as a coma separated string
$item->update_meta_data( 'category', implode( ', ', $term_names ) );
}
add_action( 'woocommerce_checkout_create_order_line_item', 'action_woocommerce_checkout_create_order_line_item', 10, 4 );
Note: add an underscore at the beginning of the meta key (like: _category
) to set any meta value as hidden order item meta data, so it's only visible on admin order edit pages