如何将以下代码片段仅应用于移动设备



代码:

add_filter( 'the_title', 'shorten_woo_product_title', 10, 2 );
function shorten_woo_product_title( $title, $id ) {
if ( ! is_singular( array( 'product' ) ) && get_post_type( $id ) === 'product' && strlen( $title ) > 30 ) {
return substr( $title, 0, 30) . '…'; // change last number to the number of characters you want
} else {
return $title;
}
}

我知道我应该在某个地方加上wp_is_mobile(),但不知道我应该在哪里添加它。

如果您想使用wp_is_mobile(),那么它只返回一个布尔值,因此您可以在包装输出的任何地方使用它:

add_filter( 'the_title', 'shorten_woo_product_title', 10, 2 );
function shorten_woo_product_title( $title, $id ) {
if ( wp_is_mobile() ) {
if ( ! is_singular( array( 'product' ) ) && get_post_type( $id ) === 'product' && strlen( $title ) > 30 ) {
return substr( $title, 0, 30) . '…'; // change last number to the number of characters you want
} else {
return $title;
}
}
return $title;
}

但是请记住,如果您使用页面缓存,移动用户可能是生成缓存的人,因此您的缓存将包含更改并到处显示。考虑到这个特定的上下文是WooCommerce,因此可能你没有缓存产品页面,如果你需要它们以某种方式是动态的,这可能无论如何都可以工作,但是@markus-ao上面的评论将是一个更好的解决方案,如果缓存是一个问题。