php - 在 Woocommerce 3 中访问 WC_Product protected 数据

标签 php wordpress class object woocommerce

我有这个答案供引用: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 methodsWC_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 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' );


官方 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/

    相关文章:

    php - 无法运行 OpenTok 的 WebRTC 演示

    jquery - 为什么使用 wp_localize_script 传递值时 jquery 选项不起作用?

    java - 将文本文件扫描到对象数组中

    java - Java 类中的数组?

    javascript - Ratchet :仍在连接状态

    php - mysql 1time 3种不同的排序

    PHP 面向对象的数据库访问

    html - 使 WP "Edge"主题全宽

    php - 所有 WordPress 选项作为单个选项(序列化多维数组)还是多个选项?

    一个文件中的 Swift 类