我需要从 woocommerce 产品变体中获取属性。
$terms = get_post_meta($value['variation_id'], 'attribute_pa_color', true);
这段代码给了我一个属性段而不是名称。如何获取属性名称?
提前非常感谢!
你得到的是分类学的一部分...... 在 WooCommerce 中,没有
attribute_pa_color
的 attribute_
是一种分类法。
所以你可以尝试这样的事情..通过 slug 来获取这个术语。并得到它的名字。
$taxonomy = 'pa_color';
$meta = get_post_meta($value['variation_id'], 'attribute_'.$taxonomy, true);
$term = get_term_by('slug', $meta, $taxonomy);
echo $term->name;
本机 WooCommerce 函数 wc_attribute_label() 是完成此任务的最简单方法。
您可以通过以下代码轻松查找属性
foreach ($product->attributes as $taxonomy => $attribute) {
foreach ($attribute->get_terms() as $term) {
var_dump($term); // term object data
}
}
我需要在购物车中显示添加产品的属性,这就是我的做法。我希望它对某人有用
<?foreach ($cart_item['variation'] as $name => $value) :
$attribute_label = wc_attribute_label(str_replace('attribute_', '', urldecode($name)), $_product);
$attribute_value = $_product->get_attribute(str_replace('attribute_', '', urldecode($name)));
?>
<span>
<?echo $attribute_label . ': ' . $attribute_value ?>
</span>
<?endforeach; ?>
请注意,在购物车页面上通常有
$_product
,在其他页面上您可能需要删除下划线 $product
。此外,在另一个页面上,您很可能会收到一个没有 attribute_
前缀的 slug。在那里指示 $attribute_name
就足够了(例如它将是 'pa_color'
) - $attribute_label = wc_attribute_label($attribute_name, $product);
属性的名称和值是西里尔字母,这导致了一些问题,因为我收到了音译的值。我不得不进行反向音译,我认为这不是一个非常正确的方法。直到现在我才做出这个决定。 我不知道这有多正确和充分,但它有效
您可以尝试以下代码。
$terms = get_the_terms( $value['variation_id'] , 'attribute_pa_color');
foreach ( $terms as $term ) {
echo $term->name;
}
让我知道这是否有帮助。另外,您可以浏览this链接中给出的解释,以获取更多信息和替代解决方案。