The deprecated "woocommerce_add_order_item_meta" hook has been a commonly used method for adding custom meta to order items. With the release of WooCommerce 2.3.7, this hook is now deprecated, leaving developers searching for an alternative.
Replacement Hook: woocommerce_checkout_create_order_line_item
Since WooCommerce 3, a new CRUD (Create, Read, Update, Delete) system has been introduced, which includes new setters and getters methods. The replacement hook for "woocommerce_add_order_item_meta" is woocommerce_checkout_create_order_line_item.
woocommerce_checkout_create_order_line_item Arguments:
This hook provides four arguments:
Usage of woocommerce_checkout_create_order_line_item:
To add custom meta to order items using this hook, you can use the following updated code:
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 ) {
// Update order item meta using the WC_Data update_meta_data() method
$item->update_meta_data( 'meta_key1', $custom_field_value );
}
Alternative: Using the Old Way
While the woocommerce_checkout_create_order_line_item hook is the recommended replacement, you can also still use the deprecated "woocommerce_add_order_item_meta" hook if needed. However, it is important to note that this hook is deprecated and may be removed in future versions of WooCommerce.
add_action( 'woocommerce_add_order_item_meta', 'custom_add_order_item_meta', 20, 3 );
function custom_add_order_item_meta( $item_id, $values, $cart_item_key ) {
// Update order item meta using wc_add_order_item_meta()
wc_add_order_item_meta( $item_id, 'meta_key1', $custom_field_value );
}
Conclusion
The woocommerce_checkout_create_order_line_item hook is the recommended replacement for the deprecated "woocommerce_add_order_item_meta" hook when using WooCommerce 3 and newer. It provides the same functionality and aligns with the new CRUD system introduced in that version.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3