It’s very simple, but useful; for instance, when you make a listing of articles on a page, but you only want to display a preview of the content of each article. Here is a small PHP function for text truncation :
if(strlen($text) > $nbrChar) {
$text = substr($text, 0, $nbrChar);
$text .= $append;
}
return $texte;
}
// Now, we apply the function to a text :
echo truncate_text(‘this is a text I\’d like to truncate at fifty characters’, 50);
// which will have as result :
// this is a text I’d like to truncate at fifty cha…
Ce message est également disponible en : French
You have a typo in your script
#
return $texte;
should be
#
return $text;
Thanks to both Guy and Lindsay.
Thank you for this handy little function!
I made a few adjustments to make it workable as a global WordPress function.
For all you WordPressers out there, just add this to your functions.php file:
function truncate_text($text, $nbrChar = null, $append = ' ...') {
if(strlen($text) > $nbrChar) {
$text = substr($text, 0, $nbrChar);
$text .= $append;
}
return $text;
}
add_action('init', 'truncate_text');
//Frankie