in Web

WP-Syntax Style Sheet Order Fix

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:

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:

Using the wp_head action puts it after all the other header links in an unpredictable order. Thankfully though, the fix is quite simple:

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:

Then I copied and modified the css from wp-syntax.css into my theme’s style.css. Saves fetching an extra file!

Write a Comment