我想在 WooCommerce 类别页面中截断带有“...”的较短标题中的长产品标题。如果我是对的,类别页面中的产品将通过“content-product.php”的循环显示。
代码是:
<li<?php echo $class ?>>
<?php do_action( 'woocommerce_before_shop_loop_item' ); ?>
<a href="<?php the_permalink(); ?>">
<div class="thumbnail">
<?php do_action( 'woocommerce_before_shop_loop_item_title' ); ?>
<?php if ( yiw_get_option( 'shop_show_name' ) ) : ?>
<strong class="<?php echo $title_position; ?>">
<?php the_title(); ?>
</strong>
<?php endif ?>
</div>
<?php do_action( 'woocommerce_after_shop_loop_item_title' ); ?>
</a>
<?php do_action( 'woocommerce_after_shop_loop_item' ); ?>
</li>
我发现了很多 PHP 函数来缩短长字符串(这个看起来很简单 http://shrtnr.us/r0yfwg ),但我无法将函数应用于 the_title()
...
如果有人能让我走上正确的道路,我将不胜感激。提前致谢:)
最佳答案
请使用此处给出的以下代码,它工作正常 - shorten-woocommerce-product-titles
只需将以下代码放入主题的 functions.php 即可完成。
// Automatically shortens WooCommerce product titles on the main shop, category, and tag pages
// to a specific number of words
function short_woocommerce_product_titles_words( $title, $id ) {
if ( ( is_shop() || is_product_tag() || is_product_category() ) && get_post_type( $id ) === 'product' ) {
$title_words = explode(" ", $title);
if ( count($title_words) > 5 ) { // Kicks in if the product title is longer than 5 words
// Shortens the title to 5 words and adds ellipsis at the end
return implode(" ", array_slice($title_words, 0, 5)) . '...';
} else {
return $title; // If the title isn't longer than 5 words, it will be returned in its full length without the ellipsis
}
} else {
return $title;
}
}
add_filter( 'the_title', 'short_woocommerce_product_titles_words', 10, 2 );
关于php - 如何在 WooCommerce 类别页面中缩短(截断)长产品标题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13828274/