Archive for August 14th, 2004

PHPizer Plugin

August 14th, 2004 by daryl

From time to time, I’ll have occasion to include some PHP code in my entries, and PHP’s a lot easier to read if it’s syntax-highlighted. Many forums allow you to wrap special tags around you code to cause it to be syntax-highlighted, and though I’ve seen some WordPress plugins out there for doing syntax highlighting, they’ve seemed a little more complicated that has seemed quite necessary, or they’ve been dependent upon some library or another being in place. So I rolled my own, which can be downloaded here.

If you want to syntax-highlight a code block, just wrap the tags <php> and </php> (replace angle brackets with square brackets) around it and this plugin filters it through the highlight_string() function. You can also specify a div class name that allows you to define a style for the container div. I’ve chosen to set my code off by putting it in a gray box with some margin and padding and a thin border. The default class name is set to “code”. The code itself for this plugin (to demonstrate the plugin in action, which strikes me as being rather like standing between two mirrors and seeing infinity as they reflect one another’s images recursively) is as follows (note that I had to screw with the code just a smidgin to keep it from parsing the php marker tags in the regular expressions — if you want to use this, download the source from the link, as that’s unscrewed-with, commented code):

[php]
$phpizer_div_class=”code”;

function phpizer($text) {
global $phpizer_div_class;
$parse=0;
$codebuffer=”";
$finaltext=”";
$count=1;

//Get lines into an array so we can iterate over them.
$lines=split(”n”,stripslashes($text));

foreach($lines as $theline){
//If we’re starting a code block, set flag and suppress marker tag display.
if(preg_match(”/[ php]/”,$theline)){
$parse=1;
$theline=”";
}
if(preg_match(”/[ /php]/”,$theline)){
$parse=0;
$finaltext .= “

n” . highlight_string(”< ?phpn" . $codebuffer . "n?>n”,1) . “

n”;
$count++;
$codebuffer=”";
$theline=”n”;
}
//Not code, so just add current line.
if($parse==0){
$finaltext .= $theline;
}
else{
$codebuffer .= $theline;
}
}
return $finaltext;
}

add_filter(’the_content’, ‘phpizer’, 8);
add_filter(’comment_text’, ‘phpizer’, 8);
[/php]