WooCommerce: Get Product Info (ID, SKU, $) from $product Object (ok) global all product
https://businessbloomer.com/woocommerce-easily-get-product-info-title-sku-desc-product-object/
Last updated
https://businessbloomer.com/woocommerce-easily-get-product-info-title-sku-desc-product-object/
Last updated
> Published: Jul 2017 - Revised: Apr 2020 > Blog Category: WooCommerce Tutorials > Blog Tags: Price, Single Product Page > Blog Comments: 51 Comments
I’ve been wanting to publish this guide for a long while. As a WooCommerce development freelancer, every day I repeat many operations that make me waste time… and one of them is indeed “How to get ____ if I have the $product variable/object?“.
For example, “How can I get the product SKU“? Or “How can I get the product short description“? Or maybe the product stock level, shipping class, tax class, price, regular price, sale price, and so on… hopefully this article will save you time.
Of course, not always you have access to the $product variable (I’m talking about WooCommerce hooks for example), so you’re also required to understand your case scenario and see if you can “get” that $product object in another way.
For example, you might know the $product_id. In this case, you have to find a way to “get the $product object from $product_id” – you find this example below.
Other examples might be the order or the cart pages. Once again, in here you don’t really have a $product available, so you have to loop through the order/cart items and “get” it. After that, you can then calculate and get any piece of information you require out of $product. Enjoy!
Hooks (do_action and apply_filters) use additional arguments which are passed on to the function. If they allow you to use the “$product” object you’re in business. Alternatively, you can declare the “global $product” inside your function.
In both cases, here’s how to get all the product information:
If you have access to the product ID (once again, usually the do_action or apply_filters will make this possible to you), you have to get the product object first. Then, do the exact same things as above.
How to get the product information inside the Order? In this case you will need to loop through all the items present in the order, and then apply the rules above.
If you wish to expand your knowledge, here’s an other article on how to get additional info out of the $order object.
How to get the product information inside the Cart? In this case, once again, you will need to loop through all the items present in the cart, and then apply the rules above.
If you wish to expand your WooCommerce PHP knowledge, here’s an other article on how to get additional info out of the $cart object.