Accessing WC_Product protected data in Woocommerce 3
The wc_get_product( $product_id)
function gives the WC_Product
instance object (from a product ID) where data can be accessed with all available WC_Product
methods and WC_Product
sub-classes depending on the product type:
// Get the instance of the WC_Product Object$product = wc_get_product( $product_id);// Using `WC_Product` methods examples to get specific related data values:$product_type = $product->get_type(); // product Type$product_id = $product->get_id(); // product ID$product_name = $product->get_name(); // product name$product_sku = $product->get_sku(); // product SKU$product_price = $product->get_price(); // product price// And so on…// The raw display of the object protected data (Just for testing)echo '<pre>'; print_r( $product ); echo '</pre>';
You can unprotect the data using the WC_Data
method get_data()
that will give you an accessible array of the data:
// Get the instance of the WC_Product Object$product = wc_get_product( $product_id);// Get the accessible array of product properties:$data = $product->get_data();// get specific related data values:$product_id = $data['id']; // product ID$product_name = $data['name']; // product name$product_sku = $data['sku']; // product SKU$product_price = $data['price']; // product price// And so on…// The raw display of the unprotected data array (Just for testing)echo '<pre>'; print_r( $data ); echo '</pre>';
For specific custom meta data you can use the
WC_Data
methodget_meta()
. So if the custom meta key is for example_custom_height
you will use:
$custom_product_height = $product->get_meta( '_custom_height' );
Official Woocommerce API Documentation: