I'm trying to pass JavaScript object using wp_localize_script() function and expecting an entitiy encoded string in the object. Below is the sample:

$params = array('str' => esc_html('this string has a < symbol and unclosed <td> tag'), 'change' => false);

wp_localize_script( 'custom_setup_js', 'custom_js_params', $params );

What is output?

/* <![CDATA[ */ var custom_js_params = {"str":"this string has a < symbol and unclosed <td> tag","change":""}; /* ]]> */

What is expected?

/* <![CDATA[ */
var custom_js_params = {"str":"this string has a &lt; symbol and unclosed &lt;td&gt; tag","change":""};
/* ]]> */

What am I doing wrong or am I misunderstanding anything? Since I need the JavaScript object to contain the encoded HTML in the string. I have already tried the same without using the esc_html() function yet no success.

PS: The string is coming from user input thus needs escaping. I have just skipped it to state the problem easier.

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged or ask your own question.