You probably know that in WordPress, for any kind of data (for example, page or post title, or post category…), you can either use the function which displays any of these data (for example the_title()), or you can only get the value (get_the_title()) without echoing and then use that value so you could apply some additional functions.
One of the great applications of this is when you need to cut the title so it could fit into the container. What kind of scenario am I talking about? For example, if you created a theme where you have columns and would like to limit the number of characters so that huge title or description does not push one element few pixels down, making the whole thing look uneven.
Even though you can always use some JavaScript code, allowing you to calculate the height of the highest column and then apply that CSS to all the columns, perhaps in some situations a better idea is to cut the title or description.
The reason for this is that if the title or content is really huge, you would have lots of empty space within other blocks, not much to the benefit of design.
Let me show you how you can easily trim the title (and you could apply this to any type of content).
1 2 3 4 5 6 |
$title_pr = get_the_title(); if (strlen($title_pr) <=63) { echo $title_pr; } else { echo substr($title_pr, 0, 63) . '...'; } |
In case you’re asking why did I use strlen(), the reason is that I don’t want to have “…” if the title is shorter than desired number of characters (in this case 63).