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

如何修改代码限制WooCommerce单个商品页的描述字符数?

修改代码实现WooCommerce单个商品页面描述字符限制

你之前直接替换钩子为description无效,是因为WooCommerce并没有这个钩子,需要使用对应商品描述的专属钩子来实现需求。以下分两种场景给出解决方案:

场景1:限制单个商品页面的商品短描述(商品摘要区域的描述)

使用woocommerce_short_description钩子,代码如下:

add_filter( 'woocommerce_short_description', 'shorten_woo_product_short_desc', 10, 1 );
function shorten_woo_product_short_desc( $description ) {
    // 仅在单个商品页面生效
    if ( is_singular( 'product' ) ) {
        // 限制为30个字符,可自行修改数字
        return substr( $description, 0, 30 ) . '…';
    }
    return $description;
}

场景2:限制单个商品页面的商品长描述(商品详情的内容区域)

商品长描述通过the_content输出,使用这个钩子并添加判断条件即可:

add_filter( 'the_content', 'shorten_woo_product_long_desc', 10, 1 );
function shorten_woo_product_long_desc( $content ) {
    // 仅在单个商品页面且当前内容是商品长描述时生效
    if ( is_singular( 'product' ) && get_post_type() === 'product' ) {
        // 限制为100个字符,可自行修改数字
        return substr( $content, 0, 100 ) . '…';
    }
    return $content;
}

额外提示

  • 可根据需求修改代码中substr的第二个参数(字符数),调整限制长度
  • 如果需要保留HTML格式(避免截断后标签未闭合),可以用wp_trim_words替代substr,示例:wp_trim_words( $description, 20, '…' )(20为单词数,中英文内容都适用)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 07:50:18