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

Limit WooCommerce product title to a specific length (and add '...')

我试图限制我们的 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;
    }
}

它有效,但我希望它在每个产品标题的末尾显示“...”。

您可以使用 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;
    }
}

代码进入活动 child 主题(或活动主题)的 functions.php 文件。已测试并有效。

我使用此代码并将字符编号更改为 40,但随后它转到第 2 行,然后添加到购物车按钮的对齐方式受到干扰,它从其他产品对齐方式中更改。

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) . '…'; // 将最后一个数字更改为您想要的字符数 } else { return $title; } }

您可以使用 CSS 通过将以下样式属性添加到包含您要省略的内容的元素来执行此操作。这将确保内容始终显示到元素的边缘,而不是 over-flowing.

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

这种方法应该比 JS 解决方案更高效,在实现这样的功能时,如果可能,我总是会选择 pure-CSS 解决方案,然后再恢复为 Javascript 或修剪字符串后端。

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