The problem with most code escape plugins
After starting this blog, I quickly realized that I need a plugin that will automatically escape html in a code block. Otherwise, it is a big pain to go through and convert all symbols to their escaped equivalents (ex: less then signs to ‘<’). I looked into a couple different solutions, but there was a major problem with them all: they convert the code on input. What this means is after you write a code block, it escapes everything inside of it, then saves it to the database. This works fine, until you need to edit your post. When you go to edit, you see ‘<’ instead of ‘<’. Not only is confusing and hard to read, but when you save it again, then it escapes everything a second time, making what is displayed on your blog incorrect.
Why my wordpress code escape plugin is different
I decided to escape the code blocks right before it is output to the page. This means that whatever you type in a code block is saved that way in the database. Because of this, you can edit posts multiple times, with no errors. When editing a post, the code in the blocks looks exactly how you typed it in, so it’s nice and easy to read. However on page everything is escaped for you. This plugin also gets rid of the ‘Smart Quotes’ that wordpress annoyingly tries to use.
Download / Install escapeCode
- download the file: escapeCode.zip
- unzip and upload to your plugins directory.
- activate it
That’s it! Nice and easy to understand code, with nothing to configure. I’ll also post the code below so if you prefer, you can copy the code and paste it into a php file you create. Enjoy!
/*
Plugin Name: escapeCode
Plugin URI: http://www.codeislogic.com
Description: Escapes HTML in Code blocks
Version: 0.01
Author: Nick Ashley
Author URI: http://www.codeislogic.com
*/
add_filter('the_content', array('nsa_contentFilter', 'escapeCode'));
class nsa_contentFilter {
function escapeCode($content) {
$str = preg_replace('/<code>(.*?)<\/code>/es', "nsa_contentFilter::formatCodeString('\\\\1')", $content);
return $str;
}
function formatCodeString($str)
{
$str = str_replace('\"','"',$str);
$str = htmlspecialchars($str);
$str = str_replace('&','&',$str);
$str = str_replace(array("‘", "’", "′"), "'", $str);
$str = str_replace(array("“", "”", "″"), """, $str);
return "<code>$str</code>";
}
}
?>