wordpress 返回产品变异属性值名称(不带连字符)

hgc7kmma  于 2022-11-22  发布在  WordPress
关注(0)|答案(1)|浏览(108)

要在WooCommerce中获取产品变体,我正在使用:

$product->get_available_variations();

但我得到的结果与连字符,见此屏幕截图:

如何获得没有连字符的结果?
谢谢

brvekthn

brvekthn1#

显然,WooCommerce是显示在这种情况下,属性slugs值,然后用连字符替换空格,用小写替换大写,这是完全正常的。所以你想显示的是属性名称(而不是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>';

}

这是经过测试和工作。

相关问题