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

如何为WooCommerce关联商品添加标题长度限制

WooCommerce关联商品标题缩短的条件标签添加方法

要让标题缩短功能作用于关联商品,你需要在原有条件中补充单个商品页的判断,同时区分主商品标题和关联商品标题,避免缩短商品详情页的主标题。

修改后的完整代码:

function short_woocommerce_product_titles_chars( $title, $id ) {
    // 新增单个商品页判断,且当前标题ID不等于主商品ID(即关联商品)
    if ( ( is_front_page() || is_shop() || is_product_tag() || is_product_category() || ( is_product() && get_the_ID() !== $id ) ) && get_post_type( $id ) === 'product' ) {
        // 标题长度超过60字符时触发缩短
        if ( strlen( $title ) > 60) {
            return substr( $title, 0, 60 ) . '...';
        }
    }

    return $title;
}
add_filter( 'the_title', 'short_woocommerce_product_titles_chars', 10, 2 );

关键修改说明:

  • 添加is_product():判断当前是否处于单个商品详情页(关联商品默认展示在此页面)
  • 补充get_the_ID() !== $id:确保只缩短关联商品的标题,不会影响详情页的主商品标题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 08:07:07