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

如何仅在移动端应用WooCommerce产品标题缩短代码?

仅在移动端缩短WooCommerce产品标题的解决方案

你只需要将wp_is_mobile()函数添加到原代码的if判断条件中,作为额外校验项,就能让标题缩短逻辑仅在移动端生效。

修改后的完整代码如下:

add_filter( 'the_title', 'shorten_woo_product_title', 10, 2 );
function shorten_woo_product_title( $title, $id ) {
    // 加入 wp_is_mobile() 条件,限制仅移动端触发标题截断
    if ( wp_is_mobile() && ! is_singular( array( 'product' ) ) && get_post_type( $id ) === 'product' && strlen( $title ) > 30 ) {
        return substr( $title, 0, 30) . '…'; // 可修改数字调整保留的字符数量
    } else {
        return $title;
    }
}

逻辑说明:

  • wp_is_mobile()是WordPress内置函数,用于识别当前访问设备是否为移动设备(手机、平板等)
  • 只有同时满足「是移动端」「非产品单页」「当前内容为产品类型」「标题长度超过30字符」这四个条件时,才会执行标题截断操作,其余场景均返回原标题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 00:25:19