2

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.

7
  • 4
    echo get_option('js_code'); ...esc_attr is escaping the value, funnily enough, so dont use that! Commented Jan 14, 2016 at 16:30
  • 1
    have you tried using html_decode? works fine ones I decode it my end. Commented Jan 14, 2016 at 16:30
  • @Steve, thanks a lot! It works for me! Maybe you post this comment as answer? Commented Jan 14, 2016 at 16:33
  • @user1779617 why encode the values (part of esc_attr) only to decode them again? Simply dont encode them in the 1st place Commented Jan 14, 2016 at 16:33
  • @TurakVladyslav Sure, give me a sec Commented Jan 14, 2016 at 16:34

2 Answers 2

2

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');
Sign up to request clarification or add additional context in comments.

Comments

1

wrap your code in this :- like this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.