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:
// code here.
Then just add the following to your site styles to prevent the pre tag from displaying:
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.
I wonder if this will lead to comment injection though..
Hi Grant, I really wanted this to work, but while plain pre tags preserve whitespace and ampersands, once I put the script tag inside the formatting gets screwed up again. Maybe it’s just my version of WordPress (now 3.7) or my server configuration?
Whitespace is no big deal, I just run the code through jsmin, but the ampersand problem I can’t figure out how to fix. Maybe stick the code in a pre and eval() it?
Plus, the post has some nifty D3.js-generated interactive charts.