ColorCode - WordPress Plugin to Highlight Code
Spent a bit of time yesterday trying to get my code examples highlighted using the GeSHi class. However using the WordPress plugin code, I found that though the code was coming up fine it was removing all paragraphs and line breaks from any surrounding text. So I then wrote my own plugin still calling the GeSHi class file, but where it displays both code and text properly.
It is still not perfect though, as it would be better to use pre for the code instead of all the spaces etc. Also need to switch to css instead of styles before XHTML 2.0 arrives, so will post an update once done.
Here is the plugin code:
Plugin Name: ColorCode
Plugin URI: http://www.nott.org/colorcode.html
Description: A filter that highlights code using the GeSHi class for over 20 languages.
Version: 1.0
Author: Mike Nott
Author URI: http://www.nott.org
*/
include(ABSPATH.‘/wp-content/plugins/geshi.php’);
function cc_callback($code)
{
$geshi = new GeSHi($code[2], $code[1], ABSPATH.‘/wp-content/plugins/geshi/’);
$geshi->set_header_type(GESHI_HEADER_DIV);
$geshi->set_url_for_keyword_group(3, ”);
$newcode = $geshi->parse_code();
return $newcode;
}
function colorcode($content)
{
return preg_replace_callback(“|<code lang=[’\”]([a-zA-Z0-9_-]+)[’\”]>(.*)< /code>|imsU”, “cc_callback”, $content);
}
remove_filter(‘the_content’, ‘wptexturize’);
add_filter(‘the_content’, ‘colorcode’, ‘1′);
add_filter(‘the_excerpt’, ‘colorcode’, ‘1′);
add_filter(‘comment_text’, ‘colorcode’, ‘1′);
[note: be sure to remove the space before the /code in the preg replace above before using]
Then just save this file as colorcode.php in your plugin folder, along with the GeSHi files.
Usage:
< code lang = " php ">
code goes here
< / code >
(but again remove spaces) ![]()