我有这个答案供引用:Woocommerce Get Product Values by ID ... 是关于功能wc_get_product()
返回 protected 数据。
为该函数定义的 getter 方法在哪里?
我如何访问内部 protected 数据 wc_get_product()
?
This Answer thread告诉我 WC_Product_Factory
正在使用类。可以扩展这个类来访问wc_get_product()
里面的 protected 数据吗? ?wc_get_product()
似乎是一个函数,但它如何返回一个对象?
最佳答案
wc_get_product( $product_id)
函数给出 WC_Product
实例对象(来自产品 ID),其中可以使用所有可用的数据访问 WC_Product
methods和 WC_Product
子类取决于产品类型:
// 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>';
您可以使用
WC_Data
method get_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' );
官方 Woocommerce API 文档:
WC_Product
list of methods WC_Product_External
list of methods WC_Product_Grouped
list of methods WC_Product_Simple
list of methods WC_Product_Variable
list of methods WC_Product_Variation
list of methods WC_Data
list of methods 关于php - 在 Woocommerce 3 中访问 WC_Product protected 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52906452/