使用woocommerce搭建的独立站网店或者商城,产品的标题有时会比较长,有的产品标题又很短,这样显示出来参吃不齐。那么Woocommerce如何缩短产品标题限制为特定长度呢,超出的部分用省略号...代替呢?
Woocommerce缩短产品标题限制为特定长度
使用strlen() PHP函数可以解决这个问题。
找到WordPress+woocommerce搭建网站主题的function.php文件,打开输入以下代码并保存。
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 ) > 100 ) {
return substr( $title, 0, 100) . '…'; // change last number to the number of characters you want
} else {
return $title;
}
}
回到产品目录页面清空缓存,刷新页面可以看到标题基本都统一长度了,排版也清晰了。
温馨提示:
以上使用了strlen() PHP函数,字符数可以修改成需要的,上面限制的100个字符。如果字符限制比较短,使用下面的代码也可以。
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') {
return substr( $title, 0, 100) . '…'; // change last number to the number of characters you want
} else {
return $title;
}
}
这段代码比前面的少了 strlen( $title ) > 100 的判断语句,结果是如果woocommerce产品标题长度小于100字符,标题末尾同样会加上省略号。
栏目