WordPress: changing your syntax highlighter easily

Switching between syntax highlighters in WordPress can be a real pain in the neck, especially when you use only shortcodes. Recently I had to test how Google Prettify works on my testing site, but all my posts were plenty of SyntaxHighlighter shortcodes. In this case you've only two options: replace shortcodes in the database or replace them by using a WordPress filter. In my opinion, the database solution is too radical, because you don't actually know if you'll need these shortcodes again in the future. So the best solution is to use a WordPress filter.

Instead of using PCRE regular expressions, I decided to use the faster str_replace() PHP function to replace shortcodes with a pre element.

Add the following code to your functions.php file:

function replace_sh_shortcodes($content) {

	$content = str_replace('[css]', '<pre class="prettyprint lang-css">', $content);
	$content = str_replace('[/css]', '</pre>', $content);
	$content = str_replace('[php]', '<pre class="prettyprint">', $content);
	$content = str_replace('[/php]', '</pre>', $content);
	$content = str_replace('[js]', '<pre class="prettyprint lang-js">', $content);
	$content = str_replace('[/js]', '</pre>', $content);
	$content = str_replace('[xml]', '<pre class="prettyprint">', $content);
	$content = str_replace('[/xml]', '</pre>', $content);
	$content = str_replace('[sql]', '<pre class="prettyprint lang-sql">', $content);
	$content = str_replace('[/sql]', '</pre>', $content);
	$content = str_replace('[text]', '<pre class="prettyprint">', $content);
	$content = str_replace('[/text]', '</pre>', $content);
	
	return $content;
}

add_filter('the_content', 'replace_sh_shortcodes');

Did it work? Absolutely. The main benefit of using a WordPress filter is that you can always get back to shortcodes if you don't like the new syntax highlighter anymore.

Back to top