I’ve been using the WordPress plugin SyntaxHighlighter to show code in posts. This worked fine, but after I was Redditted yesterday I was looking at optimizing my pages and I noticed that SH was serving up at least three files, even if it was not used on a page (which it was not, on the page that had been linked from Reddit).

So I did a little digging, and made my first plugin mod.
https://cowboyprogramming.com/2007/10/24/optional-code-in-wordpress-header/
View this Post
SyntaxHighlighter works by hooking in three actions:

add_action( 'wp_head', 'syntaxHeader' );
add_action( 'the_content', 'syntaxPost' );
add_action( 'wp_footer', 'syntaxFooter' );

The middle one does most of the work, handing a post to a syntax highlighter with the appropriate options. It’s called once per post on the page.

The other two functions respectively insert a CSS link into the page header, and a JavaScript link for each supported language into the page footer. The problem was they did this regardless of if they were actually going to be used, so every single page had these additional links, slowing down my finely tuned blog.

To fix this, I simply added this function:

// Return true if any post on this page contains the text '[source:'
function hasSyntaxPost()
{
$is_syntaxPost = false;
global $posts;
for($i=0;$i<=(count($posts)-1);$i++)
{
if( strpos( $posts[$i]->post_content, '[source:' ) !== false )
{
$is_syntaxPost = true;
}
}
return $is_syntaxPost;
}

and used it to wrap the header and footer code, like:

// Add CSS to header
function syntaxHeader() {
if (hasSyntaxPost())
{
$syntaxPath = syntaxPath();
echo "\n\t<link type=\"text/css\" rel=\"stylesheet\" href=\"{$syntaxPath}Styles/SyntaxHighlighter.css\" />\n";
}
}

That’s it. Since I know almost nothing about PHP or WordPress, I coded this with cut-and-paste coding, stealing a few lines of code from:

http://trevorcreech.com/geekery/wordpress/per-post-css/

Result: works perfectly – only pages that contain posts that need highlighting actually have the extra code added.

I then modified it to only include the languages that are used, so the user does not have to worry about setting them in the options page, and it gives an extra performance boost, as most posts will only include one language (like here I just have PHP, and on other pages I have C++).

You can see all the changed in the modified syntax.php here:

Note: When testing things like this, disable the cache until you get it working.