Accessing WC_Product protected data in Woocommerce 3

Viewed 12154

I have this answer for reference: Woocommerce Get Product Values by ID … It is about the function wc_get_product() that returns protected data.

Where are the getter methods defined for that function?
How can i access the protected data inside wc_get_product()?

This Answer thread is telling that WC_Product_Factory class is being used. Can this class be extended to access the protected data inside wc_get_product()?

The wc_get_product() seems to be a function, but how does it return an object?

1 Answers

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 method get_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:

Related