Your code is counting letters with white spaces, instead the code below is counting words without white spaces. Please See this live php file in action (here the result of your code on a string containing 25 words and mine too). Then this code is working correctly as you wish:
add_action( 'woocommerce_after_shop_loop_item_title', 'shorten_product_excerpt', 35 );
function shorten_product_excerpt()
{
global $post;
$limit = 14;
$text = $post->post_excerpt;
if (str_word_count($text, 0) > $limit) {
$arr = str_word_count($text, 2);
$pos = array_keys($arr);
$text = substr($text, 0, $pos[$limit]) . '...';
// $text = force_balance_tags($text); // may be you dont need this…
}
echo '<span class="excerpt"><p>' . $text . '</p></span>';
}
Or you can use the function from the thread below, with yours this way:
if (!function_exists('lk_limit_text'))
{
function lk_limit_text($text, $limit) {
if (str_word_count($text, 0) > $limit) {
$words = str_word_count($text, 2);
$pos = array_keys($words);
$text = substr($text, 0, $pos[$limit]) . '...';
}
return $text;
}
}
add_action( 'woocommerce_after_shop_loop_item_title', 'lk_woocommerce_product_excerpt', 35, 2);
if (!function_exists('lk_woocommerce_product_excerpt'))
{
function lk_woocommerce_product_excerpt()
{
global $post;
$content = $post->post_excerpt;
// $content = force_balance_tags($content); // may be you dont need this…
echo '<span class="excerpt"><p>' . lk_limit_text( $content, 14 ) . '</p></span>';
}
}
This should work…
This code is based on this thread: How can I truncate a string to the first 20 words in PHP?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…