2

Setting up Google Syntax Highlighter for WordPress [Updated 3 Jan 2011]

Posted (Updated ) in PHP

WordPress is great. It allows you to quickly set up a blog with minimal effort. In the case of setting up the Google Syntax Highlighter, however, it ended up being quite a hassle.

Update Jan 3 2011 To allow pre tag in TinyMCE, we’re now modifying functions.php instead of a wordpress admin file so changes aren’t erased when WP is updated. See here for more details.

Installation went fine right up until the point where I actually needed to use the thing… To use the syntax highlighter, you are meant to go to HTML view in the WYSIWYG and enter the following code:

<pre name="code" class="js">
	...
</pre>

Sound easy enough right? Wrong.

At least in WordPress 1.9.1, TinyMCE is set up to automatically cleanse your HTML resulting in the pre tag losing its attributes

<pre class="js">
	...
</pre>

After a bit of searching I stumbled upon this page. Using the initialization option specified, we can re-enable the name attribute simply by adding extended_valid_elements : “pre[class|name]” to the TinyMCE initialization. You can do this by going to your themes functions.php file and adding:

function fb_change_googlesintax_options($initArray) {
	$ext = 'pre[name|class]';
 
	if ( isset( $initArray['extended_valid_elements'] ) )
		$initArray['extended_valid_elements'] .= ',' . $ext;
	else
		$initArray['extended_valid_elements'] = $ext;
 
	return $initArray;
}
add_filter('tiny_mce_before_init', 'fb_change_googlesintax_options');

Voila! Save the file, refresh your admin page and you should now be able to use the Google Syntax Highlighter in your posts without disabling the WYSIWYG.

  • Shekhar

    Its not working with WP 3.x

    • Flynsarmy

      Hey Shekhar,

      This article is quite old now and instead I’d recommend you use WP-Syntax instead. I’ve found WP-Syntax to be superior to Google Syntax Highlighter in that the user isn’t required to load any javascript for it to work correctly and it has a pretty nice feature set.