You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取WooCommerce产品属性描述值?

获取WooCommerce产品属性描述的正确方法

场景1:获取全局产品属性的描述

如果你要获取在后台「产品 > 属性」中创建的属性本身的描述(比如属性“颜色”的描述),用以下代码:

// 替换为你的属性slug,比如'color'
$attribute_taxonomy = wc_get_attribute_taxonomy('color');
if ($attribute_taxonomy) {
    $description = $attribute_taxonomy->description;
    // 输出或处理描述内容
    echo $description;
}

场景2:获取单个产品关联属性项的描述

如果要获取某产品上具体属性选项的描述(比如产品颜色选了“红色”,要获取红色这个选项的描述),用以下代码:

global $product;
$attributes = $product->get_attributes();

foreach ($attributes as $attribute) {
    // 处理全局分类式属性
    if ($attribute->is_taxonomy()) {
        $terms = $attribute->get_terms();
        foreach ($terms as $term) {
            // 获取属性项的描述
            $term_description = $term->description;
            echo $term_description;
        }
    }
    // 自定义文本属性本身无描述字段,若需需自行扩展
}

场景3:后台产品编辑页获取属性描述

若在后台产品编辑钩子中获取,确保拿到正确的属性对象:

add_action('woocommerce_product_options_attributes', 'get_attr_desc_in_admin');
function get_attr_desc_in_admin() {
    global $post;
    $product = wc_get_product($post->ID);
    $attributes = $product->get_attributes();

    foreach ($attributes as $attribute) {
        if ($attribute->is_taxonomy()) {
            $taxonomy_obj = wc_get_attribute_taxonomy($attribute->get_name());
            if ($taxonomy_obj) {
                echo '属性描述:' . $taxonomy_obj->description;
            }
        }
    }
}

原代码失效原因

  • $attributes->description:$attributes是属性集合数组,需遍历到单个属性对象后再操作,不能直接调用description
  • $product_attribute['description']:仅当$product_attribute是wc_get_attribute_taxonomy()返回对象转换的数组时才存在该键,直接操作对象更可靠

内容的提问来源于stack exchange,提问作者Peter Dudák

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 15:45:30