Safe line breaks for Javascript integrated excerpt calls.
May 28, 2013
So there is a strange anomaly in WordPress when you send an excerpt of a post into a javascript object. If the excerpt has a line break, it will break the object and give you a javascript error.
Even if you do a nl2br() function on the excerpt.
I will show you a good way to send an excerpt or post information to the user as a javascript object and KEEP your line breaks.
It’s just a few lines of code. And is designed to do the following in PHP.
- First we will escape quotation marks so that we don’t end up closing out a string too early.
- Then will will escape all line breaks into javascript friendly line breaks
- Last we will get rid of the characters left from the excerpt that are not escaped correctly.
$excerpt = str_replace('"','\"',get_the_excerpt());
$excerpt = nl2br($excerpt);
$excerpt = str_replace(array(chr(10), chr(13)), '', $excerpt);
After this we will just send the excerpt variable as a variable in Javascript… you are all done!!