I’m trying to truncate post titles that displaying on the home page’s different kinds of widget boxes by using the following method:
I’ve inserted this into theme-functions.php
function customTitle($limit) {
$title = get_the_title($post->ID);
if(strlen($title) > $limit) {
$title = substr($title, 0, $limit) . '...';
}
echo $title;
}
Then I can replace whatever titles I want with the following code:
<?php customTitle(30); ?>
It’s working mostly fine except the website language is Simplified Chinese and apparently this truncate method doesn’t compatible with the language (I’m guessing it’s because the php is set in utf-8), it does truncate the title but it leaves an ugly question mark at the end of each title.
I’m wondering if someone can help me to change this code I used so it can compatible with utf8 and Chinese, or if there’s any other better solutions?
You can use mb_substr to get a substring by characters (instead of bytes). This way you won’t get broken characters at the end, but you may still get incomplete characters if the text uses combining marks or similar. http://us2.php.net/mb_substr