Syntax Highlighting Shortcodes in WordPress

  1. Install Easy Google Syntax Highlighter plugin.
  2. The actual highlighting library this plugin uses requires all sorts of markup and specially formatted classes to be used. It used to allow nice shortcodes, like [php], which you can re-enable. Add the following to your theme’s functions file:
// Stops WordPress from mangling our code.
// Be aware, you'll now need to explicitly include <p>...</p> tags for non-code text,
// which is why you won't see much of it here if I can help it :-)
remove_filter('the_content', 'wpautop');
remove_filter('the_content', 'wptexturize');
remove_filter('the_content', 'convert_chars');
remove_filter('the_content', 'convert_smilies');
remove_filter('the_excerpt', 'wpautop');
remove_filter('the_excerpt', 'wptexturize');
remove_filter('the_excerpt', 'convert_chars');
remove_filter('the_excerpt', 'convert_smilies');

function php_shortcode_function($attr, $content = null) {
  return get_code_output('php', $attr, $content);
}
add_shortcode('php', 'php_shortcode_function');

function js_shortcode_function($attr, $content = null) {
  return get_code_output('js', $attr, $content);
}
add_shortcode('js', 'js_shortcode_function');

function html_shortcode_function($attr, $content = null) {
  return get_code_output('html', $attr, $content);
}
add_shortcode('html', 'html_shortcode_function');

function css_shortcode_function($attr, $content = null) {
  return get_code_output('css', $attr, $content);
}
add_shortcode('css', 'css_shortcode_function');

function get_code_output($brush, $attr, $content) {

  extract( shortcode_atts( array(
      'autolinks' =&gt; 'true',
      'classname' =&gt; '',
      'collapse' =&gt; false,
      'firstline' =&gt; 1,
      'gutter' =&gt; 'true',
      'highlight' =&gt; '',
      'htmlscript' =&gt; false,
      'light' =&gt; false,
      'smart-tabs' =&gt; 'true',
      'tabsize' =&gt; 4,
      'toolbar' =&gt; 'true',
      'wraplines' =&gt; 'true'
      ), $attr ) );

  $output = '<pre>' . str_replace('&lt;&#039;, &#039;&lt;&#039;, do_shortcode($content)) . &#039;</pre>';

  return $output;
}

Now you can use the [php] shortcode and add your full code (no need to escape those < characters). Same goes for for the other shortcodes added ([plain], [html], [js], [css] etc). The shortcodes also support attributes (like highlighting of a line) as per the Syntax Highlighter Parameters.

The above code will be edited as I edit the underlying code for this site to allow for all of the Syntax Highlighter parameters. This is all very meta…

Speak Your Mind

*