Return 产品变体属性值名称(不含连字符)
Return product variation attribute values names (without hyphens)
要在 WooCommerce 中获取产品变体,我正在使用:
$product->get_available_variations();
但是我得到的结果带有连字符,请看这个截图:
如何获得没有连字符的结果?
谢谢
显然,在这种情况下,WooCommerce 正在显示属性 slugs 值,然后用连字符替换空格,用小写字母替换大写字母,这是完全正常的。所以你想要的是显示属性名称(而不是 slug)。
为此,您可以使用 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>';
}
这已经过测试并且有效。
要在 WooCommerce 中获取产品变体,我正在使用:
$product->get_available_variations();
但是我得到的结果带有连字符,请看这个截图:
如何获得没有连字符的结果?
谢谢
显然,在这种情况下,WooCommerce 正在显示属性 slugs 值,然后用连字符替换空格,用小写字母替换大写字母,这是完全正常的。所以你想要的是显示属性名称(而不是 slug)。
为此,您可以使用 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>';
}
这已经过测试并且有效。