0

Is there an excerpt output function in wordpress I can hook into regardless of the field used, rather than just the main content field?

I have a CPT using custom fields, and rather than creating a function to output only X chars, appending an ellipse while taking into account trailing whitespace etc it would seem WP already has this functionality.

  • Can't you just use the PHP trim() and substr() functions? For example, this would output the first 100 characters - substr(trim($string), 0, 100). True, no ellipse, but you are in custom function territory if you want that. – David Gard Mar 4 '15 at 14:00
  • "X chars, appending an ellipse while taking into account trailing whitespace" – myol Mar 4 '15 at 14:01
  • Why would it seem that WP already has this functionality? You may be thinking of the_excerpt()`get_the_excerpt(), but these are designed to output post content, not a custom value. – David Gard Mar 4 '15 at 14:03
  • Exactly. Hence why im asking if it can be hooked into with other content. – myol Mar 4 '15 at 14:06
2

I think that the function you need is wp_trim_excerpt. With this function you can generate a excerpt from any text:

$text = "Some context";

$excerpt = wp_trim_excerpt( $text );

It is important to note that wp_trim_excerpt use the excerpt length set by WordPress, that is 55 words by default, and make use of excerpt_lenght filter, so it will work with any plugin or theme that hook in this filter to define a custom excerpt length. If $text is greater than the excerpt length, $text is trimmed and ellips is appended. What to append can be modified using excerpt_more filter.

You may also be interested in wp_trim_words. This function uses also 55 words limit by default and it also append ellips by default. This function doesn't use excerpt_lenght filter nor excerpt_more filter. To modify the lenght and what to append you have to pass that options directly to the function:

$text = "Some context";
$words = 55;
$more = "…";

$excerpt = wp_trim_words( $text, $words, $more );
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.