I'm creating a theme in which I've created options for the admin to enter custom Javascript and Css code in the "Theme Settings" page (created using Options API).

Now I'm just not sure how to output this code in the best possible way. For the Css I've decided to use wp_add_inline_style() and update a css file, and for JavaScript I'm just echoing out the code before the wp_footer() tag, like so:

if ( $custom_js != '' ) { ?>
  <script id="theme-custom-js">
    <?php echo $custom_js; ?>
<?php }
<?php wp_footer(); ?>

All this works great but I'm not sure if I should be using any escaping functions before simply adding the css to the file or echoing out whatever the user has entered.

I've tried esc_html, esc_js and wp_json_encode, but obviously these are meant to do the opposite.

I understand that the code should be safe since it's supposedly coming from the admin, but it's just that I've taken extreme measures throughout my theme and have tried to escape almost everything right before it is echoed out. So I just feel like I should somehow do the same with this.

Please let me know about this and thank you very much.

1 Answer 1


Allowing user to control code is explicitly unsafe operation. As you note the purpose of sanitization is pretty much to not let user slip in anything executable and/or with malicious intent.

To "sanitize" executable code you would need programmatic understanding of it (code parser) and criteria engine to distinguish what is safe and what is not. For such requirements it is utopian.

Natively WordPress lets admin use JavaScript in post content. Now and then people report it as "horrible security vulnerability", but really it's just binary matter of trust — either you trust some user to input executable code or you don't. There is essentially no middle ground or "but not that code" in this case.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.