使用WooCommerce API检索产品属性数据和值



我正在尝试使用以下方法检索WooCommerce产品的产品属性:

$m = get_post_meta($pid, '_product_attributes', false);

其中$pid是我的产品的ID。

它部分起作用,但不会返回属性的值。我在wp管理员上设置了尺寸和颜色。。。

[pa_size] => Array
(
[name] => pa_size
[value] =>
[position] => 0
[is_visible] => 1
[is_variation] => 1
[is_taxonomy] => 1
)
[pa_color] => Array
(
[name] => pa_color
[value] =>
[position] => 1
[is_visible] => 1
[is_variation] => 1
[is_taxonomy] => 1
)

知道吗?

由于WooCommerce 3,您应该更好地使用WC_Product方法get_attributes(),如下所示:

$product    = wc_get_product( $pid ); // get an instance of the WC_Product Object
$attributes = $product->get_attributes(); // Get an array of WC_Product_Attribute Objects
// Loop through product WC_Product_Attribute objects
foreach ( $attributes as $name => $values ) {
$label_name       = wc_attribute_label($values->get_name()); // Get product attribute label name
$data             = $values->get_data(); // Unprotect attribute data in an array
$is_for_variation = $data['is_variation']; // Is it used for variation
$is_visible       = $data['is_visible']; // Is it visible on product page
$is_taxonomy      = $data['is_taxonomy']; // Is it a custom attribute or a taxonomy attribute

$option_values    = array(); // Initializing
// For taxonomy product attribute values
if( $is_taxonomy ) {
$terms = $values->get_terms(); // Get attribute WP_Terms
// Loop through attribute WP_Term
foreach ( $terms as $term ) {
$term_name     = $term->name; // get the term name
$option_values[] = $term_name;
}
}
// For "custom" product attributes values
else {
// Loop through attribute option values
foreach ( $values->get_options() as $term_name ) {
$option_values[] = $term_name;
}
}
// Output for testing
echo '<strong>' . $label_name . '</strong>:
<ul><li>' . implode('</li><li>', $option_values) . '</li><br>';
}

测试并工作。

最新更新