If you have worked with the text area field in meta box for WordPress themes or plugins, you already know that the line breaks in these text areas do not show up in the front-end with a regular output of
get_post_meta() function. Those of you who haven’t yet figured out how to keep and display those line breaks in front-end view, this post is for you.
So, what exactly happens in the text area field of a meta box when you make a new line and save? These new lines are saved in the database and you can see that there is nothing wrong in the output at editor view in the back-end. The problem is that when you use
get_post_meta() function to output the text data written inside the text area field, the line breaks do not show up in the front-end view although they are still there. Here are two easy ways of displaying those line breaks in front-end (for the purpose of easy understanding, let’s assume you have text area my-meta-field in a meta box and you going to
1. The PHP way: This is the easiest way, with just passing the output through a PHP function
nl2br() before using
echo. What this function does is that it inserts HTML line breaks with
<br /> tags before all newlines (
\r) data. Here is an example code:
2. The CSS way: Yes, this is my favorite way. If you don’t like those extra
<br /> tags in your HTML output and want more control over the styling of your HTML elements, this is the way for you too. What we’ll do here is that we’ll create an HTML paragraph, apply
white-space: pre-wrap in its style, and then
echo the output inside the paragraph.
white-space: pre-wrap makes that text wrap when necessary and on line breaks. Here is an example code:
One thing to mention here – the second method does not work properly for Internet Explorer versions prior to 8. But to be honest, isn’t it time we move on?
So, there you go. Two easy ways of outputting line breaks from WordPress meta box text area field. Cheers!