Insert javascript string into HTML with PHP in WP

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:

Read More
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.

Related posts

2 comments

  1. 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.

    echo get_option('js_code');
    
  2. wrap your code in this :- like this:

     html_entity_decode(esc_attr( get_option('js_code')));
    

Comments are closed.