Get Custom Values of Variations from Order Items in WooCommerce
As a WooCommerce store owner, you may often need to access the custom attribute values of product variations included in your orders. This could be for a variety of reasons – perhaps you want to display the variation details in your order emails, generate custom reports, or process the data in some other way.
However, many WooCommerce developers struggle to retrieve this information correctly. They end up using the wrong functions and accessing the wrong database tables, leading to incomplete or inaccurate results.
In this article, I'll show you the proper way to get the custom values of variations from your WooCommerce order items. We'll start by understanding the difference between order post meta data and order item meta data, then walk through step-by-step examples to extract the data you need.
By the end, you'll have a solid understanding of how to correctly access variation details within your WooCommerce orders. Let's dive in!
Understanding Order Post Meta vs. Order Item Meta
One of the main sources of confusion when working with WooCommerce order data is the difference between order post meta and order item meta. These are two separate types of metadata stored in different database tables, and they contain different information.
Order Post Meta
Order post meta is stored in the wp_postmeta
table and is associated with the overall WooCommerce order post. This meta data relates to the order as a whole, rather than individual line items. Examples of order post meta include:
- Billing and shipping details
- Coupon codes applied
- Payment method used
- Order notes
- Custom fields added to the order
To access order post meta, you would use the get_post_meta()
function, passing in the order ID as the first argument.
Order Item Meta
Order item meta is stored in the wp_woocommerce_order_itemmeta
table and is associated with each individual line item (product) within an order. This meta data contains information specific to that particular order item, such as:
- Variation attribute values
- Custom product data
- Addons or extras
- Quantities, prices, and taxes
To access order item meta, you need to use the wc_get_order_item_meta()
function, passing in the order item ID as the first argument.
It's crucial to understand the difference between these two types of meta data, as mixing them up can lead to incorrect or missing information when trying to retrieve variation details.
Accessing Variation Data from Order Items
Now that we understand the distinction between order post meta and order item meta, let's look at how to properly access the custom values of product variations within your WooCommerce orders.
The key steps are:
- Retrieve the order object
- Loop through the order's line items
- Use
wc_get_order_item_meta()
to fetch the variation data
Here's an example function that demonstrates this process:
add_action( 'woocommerce_order_status_processing', 'my_function', 10, 1 );
function my_function( $order_id ) {
$order = wc_get_order( $order_id );
foreach ( $order->get_items() as $item_id => $item ) {
$storage = wc_get_order_item_meta( $item_id, 'attribute_addon-storage', true );
$tier = wc_get_order_item_meta( $item_id, 'attribute_subscription-type', true );
// Do something with the $storage and $tier values
echo "Storage: " . $storage . ", Tier: " . $tier . "<br>";
}
}
Let's break down what's happening in this code:
- We hook into the
woocommerce_order_status_processing
action, which fires when an order reaches the "processing" status. This gives us access to the order ID.
- We use the
wc_get_order()
function to retrieve the order object associated with the given order ID.
- We loop through the order's line items using the
get_items()
method on the order object.
- For each line item, we use the
wc_get_order_item_meta()
function to fetch the values of the 'attribute_addon-storage'
and 'attribute_subscription-type'
custom attributes.
- Finally, we echo out the retrieved values for demonstration purposes.
It's important to note that the specific meta keys ('attribute_addon-storage'
and 'attribute_subscription-type'
) will depend on the custom attributes you've set up for your product variations. You'll need to replace these with the appropriate keys for your own use case.
Also, keep in mind that the wc_get_order_item_meta()
function returns a single value, so if your variation has multiple custom attributes, you'll need to call it multiple times, one for each attribute.
Verifying the Data Location
If you're still unsure about where your variation data is stored, you can use the following code snippet to output the raw order item data. This will help you identify the correct meta keys to use in your own implementation.
add_action( 'woocommerce_before_main_content', 'my_testing_order_function' );
function my_testing_order_function() {
// Define an Order ID
$order_id = 724;
// Only for admin user role
if( ! current_user_can('edit_products')) return;
$order = wc_get_order( $order_id ); // The order object
foreach ( $order->get_items() as $item_id => $item ) {
// Order item meta data Raw output
echo "<pre>ORDER ITEM META DATA - (Item_id $item_id):"; print_r($item->get_data()); echo'</pre>';
echo "<pre>ORDER ITEM META META DATA - (Item_id $item_id):"; print_r($item->get_meta_data()); echo'</pre>';
}
}
This code outputs the raw order item data and meta data for a specific order (you'll need to replace the $order_id
with the ID of an actual order in your system). It's important to note that this code should only be used for debugging purposes, as it will display sensitive order information on your website.
Once you've identified the correct meta keys for your variation attributes, you can update the earlier example code to retrieve the data you need.
Considerations and Best Practices
When working with order item meta data in WooCommerce, there are a few additional things to keep in mind:
-
Performance: Avoid making multiple calls to wc_get_order_item_meta()
within a loop, as this can negatively impact the performance of your site. Instead, try to fetch all the necessary data in a single pass.
-
Caching: Consider caching the order item meta data to reduce the number of database queries required. You can use a plugin like WP Rocket or implement your own custom caching solution.
-
Error Handling: Always check if the order item meta data exists before attempting to use it. You can do this by checking the return value of wc_get_order_item_meta()
for a non-empty string.
-
Security: When displaying order data on your site, make sure to properly escape and sanitize the output to prevent potential security vulnerabilities, such as cross-site scripting (XSS) attacks.
-
Accessibility: If you're displaying variation details in your order emails or on the frontend of your site, consider making the information accessible and easy to understand for all users.
By following these best practices, you can ensure that your WooCommerce order data retrieval is efficient, secure, and user-friendly.
Conclusion
Accessing the custom values of product variations within WooCommerce orders can be a tricky task, but by understanding the difference between order post meta and order item meta, you can effectively retrieve the data you need.
The key steps are:
- Use the
wc_get_order()
function to retrieve the order object.
- Loop through the order's line items using the
get_items()
method.
- Employ the
wc_get_order_item_meta()
function to fetch the specific variation data you require.
Remember to always verify the location of your variation data by outputting the raw order item information, and follow best practices for performance, caching, security, and accessibility.
With the guidance provided in this article, you should now be equipped to properly access the custom values of variations from your WooCommerce order items. Good luck!
Flowpoint.ai can help you identify all the technical errors that are impacting conversion rates on your WooCommerce store and directly generate recommendations to fix them
Get a Free AI Website Audit
Automatically identify UX and content issues affecting your conversion rates with Flowpoint's comprehensive AI-driven website audit.