【问题标题】:Return product variation attribute values names (without hyphens)返回产品变体属性值名称(不带连字符)
【发布时间】:2017-06-10 05:16:11
【问题描述】:

为了获得 WooCommerce 中的产品变化,我正在使用:

$product->get_available_variations();

但我得到的结果是连字符,请看这个截图:

如何获得不带连字符的结果?

谢谢

【问题讨论】:

    标签: php wordpress woocommerce attributes variations


    【解决方案1】:

    显然,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>';
    
    }
    

    这是经过测试并且有效的。

    【讨论】:

    • 谢谢,我试过了:$taxonomy = 'pa_powercord'; $meta = get_post_meta($available_variations[0]['variation_id'], 'attribute_'.$taxonomy, true);回声$元; $term = get_term_by('slug', $meta, $taxonomy); print_r($term);但它返回给我这个数组: WP_Term Object ( [term_id] => 94 [name] => North America [slug] => north-america [term_group] => 0 [term_taxonomy_id] => 94 [taxonomy] => pa_powercord [ description] => [parent] => 0 [count] => 8 [filter] => raw [term_order] => 0)
    • 那么,我怎样才能格式化分类名称,而不是 pa_powercord?
    • 不!我找到了方法,谢谢。 :)
    猜你喜欢
    • 1970-01-01
    • 2020-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-13
    • 1970-01-01
    • 2023-01-05
    • 2019-01-23
    相关资源
    最近更新 更多