gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 08:19:44 25 4
gpt4 key购买 nike

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

$m = get_post_meta($pid, '_product_attributes', false);
其中 $pid 是我的产品的 ID。
它部分工作,但它不返回属性的值。我在 wp-admin 上设置了尺寸和颜色...
[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>';
}
测试和工作。

关于php - 使用 WooCommerce API 检索产品属性数据和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65552485/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com