在Woocommerce 3中获取产品属性标签名称

7

我在Woocommerce的产品中使用了很多产品属性,并且正在通过一个表格循环遍历所有变体,该表格可以通过一个简码在产品页面上显示。

对于这个表格,我需要在表头中获取所有产品属性(这是在循环遍历变体之前),并且我使用以下方法获取属性:

$attributes = $product->get_variation_attributes();
foreach ($attributes as $key => $value) {
    echo '<td>'.&key.'</td>';
}

这不是很优雅,是吗?

那么这也可以工作:

$attributes = $product->get_attributes();
foreach ($attributes as $attribute) {
    echo '<td>'$attribute['name']'</td>';
}

无论哪种情况,我都会获取产品属性的slug。但是我需要获取标签名称,因为每个名称(术语也一样)都有Polylang翻译。

我该如何获取产品属性标签名称而不是分类法slug?


尝试使用 "var_dump" 函数输出 "$attributes" 对象。也许这能给你一些关于在循环中需要使用 "$attributes" 对象的哪个属性的想法。 - zipkundan
谢谢。这有助于我更好地理解这里正在发生的事情。不幸的是,在数组中没有获取名称,只有slug。我尝试了两个代码块。当使用第二种方法时,我获得的数组包含id、position、variation...但仍然没有实际的名称。 - Renato
1个回答

14
你将使用专门的Woocommerce函数wc_attribute_label()
foreach ($product->get_variation_attributes() as $taxonomy => $term_names ) {
    // Get the attribute label
    $attribute_label_name = wc_attribute_label($taxonomy);

    // Display attribute labe name
    echo '<td>'.$attribute_label_name.'</td>';
}

或者:

foreach ($product->get_attributes() as $taxonomy => $attribute_obj ) {
    // Get the attribute label
    $attribute_label_name = wc_attribute_label($taxonomy);

    // Display attribute labe name
    echo '<td>'.$attribute_label_name.'</td>';
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接