有多种方法可以实现这一点,如下所列。
使用wordwrap() 功能:
function shortened_description($cutlength) {
$content = get_field(\'event_short_description\');
$charcount = strlen($content);
$content = wordwrap($content, 28);
$content = explode("\\n", $content);
$shorter = $content[0];
if ($charcount >= $cutlength) {
echo $shorter . \'... <a href="\' . get_permalink() . \'">more ></a>\';
} //$charcount >= $cutlength
else {
echo $shorter;
}
}
使用
preg_match() 功能:
function shortened_description($cutlength) {
$content = get_field(\'event_short_description\');
$charcount = strlen($content);
if ($charcount >= $cutlength) {
preg_match("/^.{1,$cutlength}\\b/s", $content, $match);
echo $match[0] . \'... <a href="\' . get_permalink() . \'">more ></a>\';
} //$charcount >= $cutlength
else {
echo $content;
}
}
使用
wp_trim_words() 功能:
(注意,它将根据作为参数传递的字数修剪字符串)
function shortened_description($cutlength) {
$content = get_field(\'event_short_description\');
$shorter = wp_trim_words($content, $cutlength, \'... <a href="\' . get_permalink() . \'">more ></a>\');
echo $shorter;
}