【发布时间】:2017-06-10 05:16:11
【问题描述】:
为了获得 WooCommerce 中的产品变化,我正在使用:
$product->get_available_variations();
但我得到的结果是连字符,请看这个截图:
如何获得不带连字符的结果?
谢谢
【问题讨论】:
标签: php wordpress woocommerce attributes variations
为了获得 WooCommerce 中的产品变化,我正在使用:
$product->get_available_variations();
但我得到的结果是连字符,请看这个截图:
如何获得不带连字符的结果?
谢谢
【问题讨论】:
标签: php wordpress woocommerce attributes variations
显然,WooCommerce 在这种情况下显示,属性 slugs 值,然后用连字符替换空格,用小写替换大写,这是完全正常的。所以你想要的是显示属性名称(而不是蛞蝓)。
为此,您可以使用get_term_by( 'slug', $slug_value, $taxonomy ) 首先获取值的对象,然后获取名称值...
1) 您可以检查 get_term_by() 函数是否真的在使用该代码:
$term_value = get_term_by( 'slug', 'copper-stp-10100base-ttx', 'pa_sfp-module' );
echo $term_value->name; // will display the name value
2) 那么您的具体代码将是:
$variations = $product->get_available_variations();
$attributes = $variations['attributes'];
// Iterating through each attribute in the array
foreach($attributes as $attribute => $slug_value){
// Removing 'attribute_' from Product attribute slugs
$term_attribute = str_replace('attribute_', '', $attribute);
// Get the term object for the attribute value
$attribute_value_object = get_term_by( 'slug', $slug_value, $term_attribute );
// Get the attribute name value (instead of the slug)
$attribute_name_value = $attribute_value_object->name
// Displaying each attribute slug with his NAME value:
echo 'Product attribute "' . $term_attribute . '" has as name value: ' . $attribute_name_value . '<br>';
}
这是经过测试并且有效的。
【讨论】: