Using WP-Syntax and the visual editor

Many of the blog posts I write tend to be about web development related topics and will often include a number of code snippets. My current choice of syntax highlighter is WP-Syntax, which supports a wide range of popular languages and has the ability to also include line numbers.

The problem with using this plug-in is that the WordPress WYSIWYG Editor (TinyMCE), will remove any tags and attributes that it believes to be invalid according to it’s configuration. As two of the attributes used by this plug-in are custom attributes (escaped/line) they are removed, causing some unexpected output.

One solution to this problem is to add the custom attributes to the list of valid elements by using the ‘tiny_mce_before_init‘ filter and appending them to the ‘extended_valid_elements’ string.

The function below can be added to the functions.php file within your theme directory:

function tinymce_wp_syntax($init) {
	$values = 'pre[lang|escaped=true|line]';
	if (empty($init['extended_valid_elements'])) {
		$init['extended_valid_elements'] = $values;
	} else {
		$init['extended_valid_elements'] .= ','.$values;
	return $init;
add_filter('tiny_mce_before_init', 'tinymce_wp_syntax');

Adding this to my blog enables me to continue using the visual editor instead of disabling it and at the same time will allow the other HTML filters to continue as normal :).

Note: You may have to force refresh (ctrl + f5) the post / page editing page for the changes to take effect.

EDIT: This solution does not fully solve the problem in WordPress MU installations, as you need to adjust the allowed post tags used by the content filter.

	$allowedposttags['pre'] =  array(
		'lang' => array(),
		'escaped' => array('true' => array()),
		'line' => array()

4 Replies to “Using WP-Syntax and the visual editor”

  1. Yeah, I wondered about this already too and also wondered if a fix could be this easy. Getting up a fix would sure be the best way.

    One feature I sure miss in WP-Syntax is doing “inline code”, but I guess this might be a bit harder.

    Oh, and thanks for using GeSHi 😉


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: