Stop WordPress removing <script> tags when switching from HTML to Visual (TinyMCE)

Ok, I’ve seen solutions which go halfway to sorting out this problem, but nothing definitive, and nothing that 100% solves my problem.

Scenario:

Read More
  • In HTML mode, I add some javascript to a post I’m editing.
  • I switch to Visual, then back to HTML, and the tag and all of its content are gone.

How do I stop this from happening? I’ve tried adding custom code to my functions.php trying to access the extended_valid_elements for TinyMCE, but nothing works.

Please help!

Related posts

Leave a Reply

3 comments

  1. Adding JS to the content is very, very bad practice, and it’s just asking to be hacked.

    Add it via a shortcode, or if you really must, use a post meta/custom fields to store the js and display it after the content in your template using echo get_post_meta($post->ID,'post_javascript',true );

  2. Without mucking about with template PHP code, you can workaround the OP problem – as well as the problem where on multisite no one other than super-admin gets the unfiltered_html capability mentioned by @Tom Auger – by installing the “Shortcoder” plugin – it allows you to create “custom shortcodes” that simply render some text. This could be anything – including Javascript.

    I create a “custom shortcode” for each piece of code that I need (usually one for each page’s distinct custom code) and then the visual editor sees the shortcode and doesn’t remove it.

    Its also great for Javascript code re-use, if you have multiple pages that need the same (or similar) code.