我使用以下代码自动缩短静态主页主商店、类别和标签页面上的 WooCommerce 产品标题。我也想对相关产品这样做。我应该在此处为相关产品添加什么条件标签
此代码会自动将静态主页主商店、类别和标签页面上的 WooCommerce 产品标题缩短为设定的字符数
function short_woocommerce_product_titles_chars( $title, $id ) {
if ( ( is_front_page() || is_shop() || is_product_tag() || is_product_category() ) && get_post_type( $id ) === 'product' ) {
// Kicks in if the product title is longer than 60 characters
if ( strlen( $title ) > 60) {
// Shortens it to 60 characters and adds ellipsis at the end
return substr( $title, 0, 60 ) . '...';
}
}
return $title;
}
add_filter( 'the_title', 'short_woocommerce_product_titles_chars', 10, 2 );
最佳答案
以下内容也会将您当前的代码扩展到相关产品:
function shorten_woocommerce_loop_product_titles( $title, $id ) {
global $woocommerce_loop;
if ( ( is_front_page() || is_shop() || is_product_tag() || is_product_category() || ( isset($woocommerce_loop['name'])
&& $woocommerce_loop['name'] === 'related' ) ) && get_post_type( $id ) === 'product' ) {
$length_threshold = 60; // Here define the desired number of characters max to be displayed
// If the product title is longer than xx characters
if ( strlen( $title ) > $length_threshold ) {
// Shortens it to xx characters and adds ellipsis at the end
return substr( $title, 0, $length_threshold ) . '...';
}
}
return $title;
}
add_filter( 'the_title', 'shorten_woocommerce_loop_product_titles', 10, 2 );
代码位于子主题的functions.php 文件中(或插件中)。经过测试并有效。
关于php - 如何限制 woocommerce 中相关产品的标题长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76930842/