If you treat WordPress exclusively as a blogging application or, even in a more liberal sense, a content management system, then you’re likely used to using the editor or the excerpt field to write a teaser then introduce a Read More link.

WordPress for Web Applications (Again)

For those who have read this site for a while, I’m specifically interested in using WordPress as a foundation for web application development (see also this, this, this, and this).

WordPress for Web Applications

At the time of this post, this is an article that’s about six years old.

So there are times when the content that you’re going to be rendering on the front-end may be coming from a third-party source.

Back to the Content

That is, the application works like this:

  1. contact a third-party API,
  2. import data from the call and parse it as necessary,
  3. write it to the database,
  4. render the information on the front-end when requested.

There’s a lot that can go in between each of the above steps, but the main thing I want to share in this post is an effective way to easily truncate text using PHP to render on the front-end.

This is useful for providing teasers, linking out to third-party sites, and more all without needing to write or edit content manually.

Easily Truncate Text in PHP

To give a sample use case for the function I’m going to share, it’s useful to have some requirements. They are arbitrary for this post but the implementation should be concrete enough that you can drop this into the post without any problems.

Let’s assume:

  • we’re pulling text from a third-party API,
  • the data is stored somewhere within the database,
  • the data is plain text (no markup or any other type of web-based entities in the structure),
  • we need a function that accepts the text and a length to truncate the text.

Given those requirements, we can set up a function to accept text and a length of arguments. If the text is less than or equal to the specified length, there’s nothing to do; otherwise, we can truncate the text to the specified length and add trailing ellipses.

Here’s the code:

Implementations for this in the context of WordPress could come from reading data stored in custom tables, in the post meta data, in the post table, or basically in any place that raw text is stored and you want to render it on the front-end.

Should there be other content in the text like HTML or other entities, there may need to be allowances made. If it’s in WordPress, there are filters and other forms of handling that data before truncating the text, but that’s beyond the point of easily truncating text in PHP, right?

So, at least, use this purely for text and, at most, make allowances for other types of content in the text before passing it into preg_replace and you should be good to go.