highlighting php source code in WordPress

March 11th, 2005. Tagged: WordPress

The source code highlighting was probably the first feature I was missing in WordPress. I briefly googled my options and decided it would be quicker to add the missing feature myself, since it looked pretty straightforward.

So what I did:
1. I added a hilite() function in functions-formatting.php
<?php

function hilite($text)

{

    $text = str_replace('<? php', '<?php', $text);

    return preg_replace_callback(

             "'<\?php.*?\?>'si",

             create_function(

                 '$matches',

                 'return highlight_string($matches[0], true); '

             ),

             $text);

}

?>

The first line of the function is pretty curious, I agree. I needed it because I noticed that WP is adding a space between < and ? before saving to the database.

2. I added call to the new function in default-filters.php

add_filter('the_content', 'hilite');

... just before this line

add_filter('the_content', 'wptexturize');

And it worked! Only that the highlighting itself for some reason is using the HTML font tag (God forbid!), but I believe that's server setup.

Edit:
I added the filter to one more place in default-filters.php, in order to highlight source code when listing excerpts, for example category listing on an archive listing. So default-filters.php looks more like:
add_filter('the_content', 'hilite');
add_filter('the_content', 'wptexturize');
add_filter('the_excerpt', 'hilite');
add_filter('the_excerpt', 'wptexturize');

Tell your friends about this post: Facebook, Twitter, Google+

Sorry, comments disabled and hidden due to excessive spam. Working on restoring the existing comments...

Meanwhile, hit me up on twitter @stoyanstefanov