How to Get Certain Values from a Woocommerce Product
I find it difficult to understand how to get Woocommerce product values.
Most searches for how to simply get the price or SKU so you can display it somewhere in your theme point to Stackexchange forums where long blocks of code are suggested, and often chosen as the best answer. I’m a fan of minimal code, and so writing five lines of code just to get a single value seems ridiculous.
Why doesn’t Woocommerce just have functions like WordPress’
the_content()? This baffles me all the more now that Automattic, basically the company created by the guy who created WordPress (it’s a longer story than that, but that’s pretty accurate.)
For example, why can’t all of the functions on this page just work–or have working equivalents–without throwing fatal errors like:
Fatal error: Uncaught Error: Call to undefined function get_sku()...
Luckily, for many values a Woocommerce product has, you can use built in WP functions. For example, if you want to get the SKU for a product in your content-single-product.php template, just do this:
<?php echo get_post_meta(get_the_ID(), '_sku', true); ?>
This is a standard WordPress function. It just looks for post meta in the
wp_postmeta database table. It’s used all the time by developers to show content from custom fields we create.
That function has three arguments. The first, where I have
get_the_ID(), defines which post to retrieve the post meta data from. That
get_the_ID(), when used in the loop, will get the current product’s ID.
The second function,
'_sku', determines which post meta field we should look for. I want the SKU, and looking in the database I see that
_sku is the name of the meta field.
true argument simply says to only get one value, the latest, so the function doesn’t return an array instead of the actual value.
Here are other various values you can use in lieu of
_sku. If you need something you don’t see here, try looking in the database’s
wp_postmeta table, and search for the product’s ID via the
- Whether the product is in stock or not.
- Does this have the “download” checkbox checked?
- Does it have the “virtual” checkbox checked?
- The price.
- The sale price, if one has been added.
- The product’s various dimensions or weight (these should be used individually.)
- The start and end dates for the sale (should be used individually.)
- Whether backorders are allowed.
- How many items are in stock?
- What amount of stock for this product will trigger the low stock threshold?