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

在WooCommerce分类页面显示产品自定义字段的相关问题

WooCommerce 自定义字段与产品摘要显示优化方案

1. 实现自定义字段优先显示,无字段则显示摘要

将你原来的两个函数合并为一个,通过判断自定义字段是否存在来切换显示内容,避免二者同时出现:

// 删除你原来的两个函数,用这个替代
add_action( 'woocommerce_after_shop_loop_item_title', 'display_custom_field_or_excerpt', 5 );  
function display_custom_field_or_excerpt() {
    global $post;
    // 仅在商店、分类、标签等列表页生效
    if ( is_home() || is_shop() || is_product_category() || is_product_tag() ) {
        $custom_text = get_post_meta( $post->ID, 'customtext', true );
        
        if ( ! empty( trim( $custom_text ) ) ) {
            // 自定义字段存在且非空时显示
            echo '<span class="excerpt">' . $custom_text . '</span>';
        } else {
            // 无自定义字段时显示产品摘要
            echo '<div class="my-excerpt">' . wp_trim_words( $post->post_excerpt, 50 ) . '</div>';
        }
    }
}

2. 限制自定义字段的字数/字符数

限制单词数(适合英文场景)

使用WordPress内置的wp_trim_words()函数,指定保留的单词数量:

// 替换上述代码中输出自定义字段的行
$trimmed_text = wp_trim_words( $custom_text, 30 ); // 保留30个单词,可自行修改数量
echo '<span class="excerpt">' . $trimmed_text . '</span>';

限制字符数(适合中文/多语言场景)

使用mb_substr()实现字符级截断,支持中文等多字节字符:

// 替换上述代码中输出自定义字段的行
$max_length = 60; // 设定最大字符数
$trimmed_text = mb_strlen( $custom_text, 'UTF-8' ) > $max_length 
    ? mb_substr( $custom_text, 0, $max_length, 'UTF-8' ) . '...' 
    : $custom_text;
echo '<span class="excerpt">' . $trimmed_text . '</span>';

3. 调整显示位置到标题下方、价格上方

WooCommerce中,产品价格的钩子优先级为10(挂载在woocommerce_after_shop_loop_item_title下)。要让内容显示在价格之前,只需将你的函数优先级设为小于10(示例中设为5),这样会先于价格执行并渲染。

上述代码已经将优先级设为5,直接使用即可。若需调整,修改add_action中的第三个参数即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 17:40:20