Ok, I’ve seen solutions which go halfway to sorting out this problem, but nothing definitive, and nothing that 100% solves my problem.
Scenario:
- 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!
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 );
This can be quite easily done by granting the
unfiltered_html
capability to whichever role you’re interested in allowing SCRIPT and IFRAME tags. Obviously, as mentioned by others, there’s inherent security risks, so be judicious about it.To learn more about granting capabilities, see The WordPress Codex entry on add_cap().
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.