If you’re familiar with WordPress theme development, you know that string length can really be a problem. You have a specific and well-crafted design, but you have to keep in mind that if you’re not careful, users could break it by using strings that are too long (like titles, or category names, and so on…). For that reason among others, it could be useful to think about a way to limit the length of a string – and that’s exactly what we’re going to do in this post.
Let’s dive into it!
How to limit a string in PHP
The fastest way to do this is to create a function we can use every time we want. So let’s go in our functions.php
and create the following function:
function theme_limit_string( $string, $limit, $end = "..." ){ $string = explode( ' ', $string, $limit ); if( count( $string ) >= $limit ){ array_pop( $string ); $string = implode( " ", $string ) . $end; } else { $string = implode( " ", $string ); } echo $string; }
So, what did we do here?
First of all, we created a function that cuts a string after a certain number of characters. The function here accepts three arguments:
- $string, which is the actual string we want to limit;
- $limit, the number of characters after we want to cut the string;
- $end, that is what we want to echo after the string is cut (default here is “…”, but you can choose whatever you want).
So, calling this function is quite simple, and we can just do this, from wherever we want in the theme:
theme_limit_string( "This is a string we totally want to limit!", 16 );
So we just called the function passing it the string, and a limit of 10 characters. The output will be:
This is a string...
We didn’t pass the third argument to the function, because it already has a default value.
That, of course, is just an example of a function. You can edit it to fit your needs, to add string escaping and so on.