When you include javascript in a WordPress post, WP automatically applies formatting to the script tag’s contents, causing script errors. This has led to a large number of workarounds, including: plugins, using custom fields, including every script as a separate JS file, and stripping empty lines from the script (to prevent WP from injecting paragraph tags).
I wanted a solution that would let me quickly inject JS directly into my post content, and wouldn’t require any special prep or have dependencies on third party plugins. After unsuccessfully hunting the web for an answer, I came up with a simple approach that uses a pre tag to prevent WordPress from formatting my code:
<pre class="script"><script>
// code here.
</script></pre>
Then just add the following to your site styles to prevent the pre tag from displaying:
pre.script {
visibility: hidden;
display: none;
}
It’s crazy simple and the script executes properly. I’m kind of shocked that I didn’t run into this approach at all in my search. It makes me worry a bit that there’s some glaring flaw with it, but so far it seems to be working great.
Hopefully this saves someone else some time and frustration.
Note: there’s a chance you may need to disable “Settings > Writing > WordPress should correct invalidly nested XHTML automatically” to prevent WP from encoding characters in your code. I have it disabled normally, but in limited testing I didn’t see any problems with it enabled.