Woocommerce get variation meta data PHP
This code goes in your WordPress child theme functions.php or your plugin script.
Assuming you or a plugin has added a custom field to your product variations in WooCommerce; you will probably want this information later e.g., to tell the customer what they bought exactly or to work out the profit on your product so the commission can be paid to your sales force. In our case, we added a “product cost price” as a variation custom field.
Our variation prices vary a gold widget costs more than a plastic widget.
In order to calculate the total cost price of the sale, we have had to multiply the value by the quantity bought. Once we have the value we can add a new meta record to the post order item meta.
PHP to get variation meta and add it to the order item meta
To summarise, when an item is added to the cart, we loop through cart items find the variation id and look up its associated meta data. This data is then stored for later using $item->update_meta_data
MYSQL Query for retrieving custom meta added to the WooCommerce order
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 ) { foreach( WC()->cart->get_cart() as $cart_item ){ // Get the WC_Product object (instance) $cartqty = $cart_item['quantity']; $variation_id = $cart_item['variation_id']; $custom_field_value = get_post_meta( $variation_id, 'YOUR CUSTOM FIELD NAME', true ); $cost_line_total = $cartqty * $custom_field_value; } if ( ! empty( $custom_field_value ) ){ $item->update_meta_data( 'cost_line_total', $cost_line_total ); } }
SQL For Reporting
We have then queried the post in the myphp database to create a Sales Commission Table in wp-admin. This is just a section of our code.
select DISTINCT i.order_item_id, im.meta_key as YOUR CUSTOM FIELD NAME, im.meta_value as amount inner join wp_woocommerce_order_itemmeta as im on i.order_item_id = im.order_item_id where p.post_type = 'shop_order'
I hope this post saves developers alot of time
Here are some related articles
https://stackoverflow.com/questions/45256561/woocommerce-3-1-product-variation-meta-data