php 将WooCommerce产品标题限制为特定长度(并添加'...')

cngwdvgl  于 11个月前  发布在  PHP
关注(0)|答案(4)|浏览(181)

我试图限制我们的WooCommerce产品标题的字符数,我发现了这个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' ) {
        return substr( $title, 0, 30); // change last number to the number of characters you want
    } else {
        return $title;
    }
}

它的工作,但我希望它显示的“...”在每个产品标题结束。

vxqlmq5t

vxqlmq5t1#

您可以使用strlen() 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 ) > 30 ) {
        return substr( $title, 0, 30) . '…'; // change last number to the number of characters you want
    } else {
        return $title;
    }
}

代码放在活动子主题(或活动主题)的functions.php文件中。测试和作品。

qxgroojn

qxgroojn2#

我用这个代码,并改变字符数为40,但然后它去第二行,然后对齐添加到购物车按钮干扰,它得到改变从其他产品alignmen .
add_filter('the_title','shorten_woo_product_title',10,2);功能shorten_woo_product_title($title,$id){ if(!是_单数(数组('产品'))&&得到_后_类型($id)=== '产品' && strlen($title)> 30){返回substr($title,0,30).'...'; //将最后一个数字更改为所需的字符数} else { return $title;{\fnSimHei\bord1\shad1\pos(200,288)}

j13ufse2

j13ufse23#

您可以使用CSS将以下样式属性添加到包含要省略的内容的元素中来实现此目的。这将确保内容始终显示到元素的边缘,而不会溢出。

white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;

这个方法应该比JS解决方案更有性能,当实现这样的功能时,我总是选择一个纯CSS解决方案,如果可能的话,然后再恢复到JavaScript或在后端修剪字符串。

33qvvth1

33qvvth14#

white-space: nowrap;
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
text-overflow: ellipsis;
overflow: hidden;

相关问题