Fixing Code in Wordpress Posts

Ever have Wordpress eat some code in your post? Replaced your >’s or “s with HTML friendly versions did it? Even when you’re running a nice syntax highlighting plugin like Crayon (my new fav) or Syntaxhighlighter Evolved (my old fav)? I have. Just now in fact. Here’s how I generally fix that.

Two things to note:


  1. Before you try running any updating/deleting SQL on your Wordpress database, back that thing up. You have been warned.

  2. If you plan on sticking code in your post more than once in your life, use something like Crayon. If you are just dumping code on a page, you really have to have the HTML friendly markup in there and this won’t help you.

– clean up the posts database a bit by getting rid of revisions - this is optional
delete from wp_posts
where post_type = ‘revision’;

– Replace the HTML replacements for <, >, and “ with what they should be
– Note I make some assumptions on my code container syntax, like [javascript
– The more you can narrow down queries like this, the better
update wp_posts
set post_content = replace(post_content, ‘&gt;’, ‘>’)
where post_content like ‘%[php%’ or
post_content like ‘%[javascript%’ or
post_content like ‘%[html%’ or
post_content like ‘%[css%’ or
post_content like ‘%[text%’;

update wp_posts
set post_content = replace(post_content, ‘&lt;’, ‘<’)
where post_content like ‘%[php%’ or
post_content like ‘%[javascript%’ or
post_content like ‘%[html%’ or
post_content like ‘%[css%’ or
post_content like ‘%[text%’;

update wp_posts
set post_content = replace(post_content, ‘&quot;’, ‘“‘)
where post_content like ‘%[php%’ or
post_content like ‘%[javascript%’ or
post_content like ‘%[html%’ or
post_content like ‘%[css%’ or
post_content like ‘%[text%’;
After that, going in to phpMySQLAdmin or what have you and optimizing your tables isn’t a bad idea.