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+

5 Responses

  1. Nice simple little method thanks, after looking at the PHP manual is appears as though font tags are used in PHP 4 and span tags in PHP 5:
    http://php.net/highlight_string

  2. Fine actual practice? I completely loved the post. Please location a lot more frequently
    if there is certainly time. Thanks Add

    my page: Claudette

  3. Hi, Neat post. There’s an issue along with your site in internet explorer,
    could check this? IE still is the marketplace leader and a huge section of other people
    will leave out your wonderful writing because
    of this problem.

  4. The two murdered troopers, Power and Cahill, were men from good Irish families.

    Not only does a digger know that it is quite possible he or she locate a good deal
    of gold with almost no trouble, but, worse still, he knows he might work very hard
    without getting any gold at all. Just as your
    swelling fails just a little in reply towards the diuretic doesn’t
    imply you are getting better.

  5. Why visitors still use to read news papers when in this technological globe everything
    is accessible on web?

Leave a Reply