Migrate from CodeHighlighter to SyntaxHighlighter without altering past posts

April 2, 2015

For many long years this site has used the CodeHighlighter plugin to markup code. CodeHighlighter’s last update was in 2012, that is eons in computer time. If you paid attention you will notice that CodeHighlighter is one of my plugins. Why am I switching away you ask? CodeHighlighter’s code base is old, real old. It was old when I inherited the plugin and it needs a rewrite. A very significant rewrite that I simply do not have the time to do now. Alix Mills has a great plugin called SyntaxHighlighter that is currently maintained with regular updates so I am making the switch. The caveat is that CodeHighlighter and SyntaxHighlighter both use different syntax to mark code.

CodeHighlighter uses pre tags with a source language attribute like:

[html]
<pre lang=\"php\">echo ‘Hello World’;</pre>
[/html]

While SyntaxHighlighter uses shortcodes named by the language like:

[html]
[ php]echo ‘Hello World’;[/php]
[/html]

While making the switch I had two options; 1) Updates all the posts with markup (literally hundreds) or 2) Filter the CodeHighlighter marked on the fly into SyntaxHighlighter. I chose the second.

After strugglebussing with Ian Dunn and AJ Mallory at WordCamp Seattle I finally came up with a solution that is very quick and so far seems to work on all my posts. Drop this code somewhere and it will act as a shim, rewriting posts code markup on the fly, and very quickly too!

[php]
add_filter( ‘the_content’, function( $content ) {

if( 2 == get_current_user_id() ) {

$regex = ‘#\<pre lang=\"(.*)\"\>(.*)?\</pre\>#Uis’;
preg_match_all( $regex, $content, $matches, PREG_SET_ORDER );

foreach( $matches AS $m ) {
//echo ‘<pre>’; var_dump( $m );
$new_c = str_replace( ‘<pre lang="’ . $m[1] . ‘">’, ‘[‘ . $m[1] . ‘]’, $m[0] );
$new_c = str_replace( ‘</pre>’, ‘[/’ . $m[1] . ‘]’, $new_c );
$content = str_replace( $m[0], $new_c, $content );
}
return $content;
}

return $content;
}, 1);

[/php]

Leave a Reply

Your email address will not be published. Required fields are marked *