0

I have a site where I am listing titles, and since each title is larger than our needed space I have to use the following code to break it down if it is larger than a certain amount of characters, and then show ...:

<?php $title = get_the_title(); echo mb_strimwidth($title, 0, 45, '...'); ?>

Is there a way to possibly list only a certain amount of words, instead of characters, so we can at least have a full word at the end of the title instead of a character and then ...?

Any help would be greatly appreciated. This is on a WP system.

Zach Smith
  • 5,490
  • 26
  • 84
  • 139

3 Answers3

1

You could for example use wordwrap() function and then discard all lines except the first one.

Mchl
  • 61,444
  • 9
  • 118
  • 120
1

This is a very common question, asked and answered many times on SO. Here are two solutions:

Trim headline to nearest word
Trimming a block of text to the nearest word when a certain character limit is reached?

Community
  • 1
  • 1
brian_d
  • 11,190
  • 5
  • 47
  • 72
0

Since you're using multi-byte string functions, you can do:

if (mb_strlen($title) > 45) {
    $title = mb_substr($title, 0, 45);
    // make sure it ends in a word by chomping at last space
    $title = mb_substr($title, 0, mb_strrpos($title, " ")).'...';
}

echo $title;
webbiedave
  • 48,414
  • 8
  • 88
  • 101