0

I am trying to create a Javascript function that echoes out a Wordpress function called the_title() which just returns the title of the a blog. Through PHP it echoes out fine but when I do it through Javscript, however, quotes seem to be unescaped (specifically single quotes). Any help or explanation why this is happening?

THE CODE:

function createSliderTabs() {   
    var para = document.createElement("li");
    var strings = "<?php the_title(); ?>";
    var post_string = strings.replace(/"/g, "").replace(/'/g, "").replace(/\(|\)/g, "");
    var node = document.createTextNode(post_string);
    para.appendChild(node);
    var element = document.getElementById("control-navigation");
    element.appendChild(para);
}

    createSliderTabs();

THE RESULT:
Macy&#8217 ;s Herald Square (had to include space or it would've changed to single quote)

WHAT IT SHOULD BE:
Macy's Herald Square

Any help or guidance on why this is happening? Thx in advance...

Dave
  • 57
  • 9
  • WordPress is printing the title with `’`. And as you use a text node which can’t contain HTML, you see `’` and not `’`, the character which `’` refers to. – Gumbo May 30 '14 at 22:58
  • Oooo....any direction on how to escape it or convert it? – Dave May 30 '14 at 23:02
  • Perhaps make node a span rather than a textnode, and set its innerHTML to post_string? That might not work, just throwin' out ideas. – Pete Scott May 30 '14 at 23:15

2 Answers2

2

From php to js transformation you always have to use json_encode().

Community
  • 1
  • 1
inf3rno
  • 24,976
  • 11
  • 115
  • 197
-1

You can use html_entity_decode:

I'm not really familiar with wordpress, but I suppose you would use it inside the_title():

function the_title()
{
   $str = 'Macy&#8217;s Herald Square';
   echo html_entity_decode ($str, ENT_COMPAT , "UTF-8");
}

If you need to use json_encode() you should be able to do

$json = html_entity_decode(json_encode($array), ENT_COMPAT , "UTF-8");

EDIT: added ENT_COMPAT , "UTF-8"

developerwjk
  • 8,619
  • 2
  • 17
  • 33