I’m using Ryan McGeary‘s excellent WP-Syntax plugin for syntax highlighting of code in WordPress. [It is now maintained by Steve Zahm.]
Update [7 Apr 2014]: I’m, uh, no longer using Ryan’s WP-Syntax plugin… I switched to Crayon Syntax Highlighter so I could have more control over the layout. The examples below are using Crayon now.
Without the plugin, simply using the <code> tag, code looks like this:
/* Hello World program */
#include <stdio.h>
int main( int argc, char *argv[] ) { printf("Hello World");
return 0; }
With the WP-Syntax plugin, it is formatted to make it much more readable:
1 2 3 4 5 6 7 8 9 10 |
/* Hello World program */ #include <stdio.h> int main( int argc, char *argv[] ) { printf("Hello World"); return 0; } |
One problem with the plugin though is that the CSS style sheet for the plugin is being included after some external Javascript in the head element of the HTML document. This prevents some browsers from loading the CSS in parallel which can delay loading of the page. A good way to catch these kinds of things is to use Google’s Page Speed plugin.
The problem can be traced back to the way the style sheet is included in the plugin’s php in the plugins/wp-syntax/wp-syntax.php file:
1 2 3 4 5 6 7 8 9 10 11 |
function wp_syntax_head() { $css_url = WP_PLUGIN_URL . "/wp-syntax/wp-syntax.css"; if (file_exists(STYLESHEETPATH . "/wp-syntax.css")) { $css_url = get_bloginfo("stylesheet_directory") . "/wp-syntax.css"; } echo "\n".'<link rel="stylesheet" href="' . $css_url . '" type="text/css" media="screen" />'."\n"; } add_action('wp_head', 'wp_syntax_head'); |
Using the wp_head action puts it after all the other header links in an unpredictable order. Thankfully though, the fix is quite simple:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
function wp_syntax_head() { $css_url = WP_PLUGIN_URL . "/wp-syntax/wp-syntax.css"; if (file_exists(STYLESHEETPATH . "/wp-syntax.css")) { $css_url = get_bloginfo("stylesheet_directory") . "/wp-syntax.css"; } wp_register_style( 'wp-syntax', $css_url ); wp_enqueue_style( 'wp-syntax' ); } add_action( 'wp_print_styles', 'wp_syntax_head' ); |
This is explained pretty well on the wp_enqueue_style reference page, but essentially setting it up this way tells WordPress to queue up the CSS file to put it in the proper place in the head element instead of after everything else.
One of the other advantages to this method is that it makes it easy to replace the included wp-syntax.css file. For example, I wanted to include the css in my theme’s style.css file instead of having it load an extra css file for this. In my theme’s functions.php, I added:
1 2 3 4 5 6 7 |
// remove the wp-syntax style since we're including it in our own css add_action( 'wp_print_styles', 'deregister_some_styles', 100 ); function deregister_some_styles() { wp_deregister_style( 'wp-syntax' ); } |
Then I copied and modified the css from wp-syntax.css into my theme’s style.css. Saves fetching an extra file!