I need to create some widget for WP and in widget’s setting will be textarea
, where user can insert some JS code. And then my widget must inject this code to WP’s footer.php
with this function:
add_action( 'wp_footer', 'inject_js', 10 );
In my inject_js
I have:
function inject_js () {
echo esc_attr( get_option('js_code') );
}
Everything is working good and the code inserts into HTML, but I faced one problem. In my HTML I get something like this:
<!-- BEGIN JS widget -->
<script type="text/javascript">
var __cp = {
id: "J4FGckYPdasda21OaTnqo6s7kMgeGXdTBAb6SgXMD-A"
};
As I understand I got the code from user’s textarea
in string
type and I must do something with the quotes and other symbols, but I really don’t know how to solve this issue, because I am new to PHP.
What PHP function must I use or it’s possible to do with some WP functions?
I tried:
echo htmlspecialchars(esc_attr( get_option('js_code') ));
and
echo addslashes(esc_attr( get_option('js_code') ));
But nothing helped.
You are seeing the effect of
esc_attr
– the function is html encoding (amoungst other things) the string.It is designed for untrusted user input. As your code is specifically designed to accept javascript from a trusted source (the site owner), dont use it.
wrap your code in this :- like this: