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

WooCommerce:调整单品页面Attribute(属性)的显示位置

解决WooCommerce单品页属性移至分类/标签区域的问题

问题分析

你当前代码通过woocommerce_single_product_summary钩子(优先级25)输出属性,这个位置默认在加购按钮附近。而分类、标签属于产品元信息区域,对应WooCommerce的woocommerce_product_meta_start系列钩子,需要调整挂载钩子并优化代码精准显示目标属性。

修改后的代码

替换你当前的代码,将以下内容添加到主题的functions.php文件中:

function display_difficulty_attribute() {
    global $product;
    
    // 替换为你后台"Difficulty"属性的实际slug(通常是pa_difficulty)
    $target_attribute = 'pa_difficulty';
    
    $attribute_value = $product->get_attribute($target_attribute);
    if (empty($attribute_value)) {
        return;
    }
    
    // 获取属性的官方显示名称
    $taxonomy = get_taxonomy($target_attribute);
    $attribute_label = $taxonomy->labels->singular_name ?? 'Difficulty';
    
    // 输出和分类/标签一致格式的内容
    echo '<span class="tagged_as"><strong>' . esc_html($attribute_label) . ':</strong> ' . esc_html($attribute_value) . '</span>';
}
// 挂载到产品元信息起始位置,和分类、标签同区域
add_action('woocommerce_product_meta_start', 'display_difficulty_attribute', 10);

代码说明

  • 精准筛选属性:通过属性slug仅显示"Difficulty"属性,避免输出所有产品属性。
  • 钩子调整:使用woocommerce_product_meta_start钩子,直接将属性插入分类、标签所在的元信息区块。
  • 样式统一:输出的HTML结构和分类、标签完全匹配,确保页面样式一致。

额外调整提示

  • 若想让属性显示在分类之后、标签之前,可将函数优先级改为15(分类默认优先级10,标签默认20)。
  • 确认属性slug:后台进入产品 > 属性,找到"Difficulty"属性,查看其slug值并替换代码中的$target_attribute。

内容的提问来源于stack exchange,提问作者user3638389

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 22:48:19