Add [raw] shortcode to display code

NOTE: This code appears to fail in WP 3.0.  Use the SyntaxHighlighter Evolved plugin instead.

Put the code below in your functions.php file to add the [ raw] … [ /raw] shortcode (without the spaces) for displaying code in your posts:

<?php
function raw_formatter($content) {
  // Shortcode [ raw] ... [ /raw] to preserve code formatting
	$new_content = '';
	$pattern_full = '{(\[raw\].*?\[/raw\])}is';
	$pattern_contents = '{\[raw\](.*?)\[/raw\]}is';
	$pieces = preg_split($pattern_full, $content, -1, PREG_SPLIT_DELIM_CAPTURE);

	foreach ($pieces as $piece) {
		if (preg_match($pattern_contents, $piece, $matches)) {
        $new_content .= htmlspecialchars($matches[1]);
		} else {
			$new_content .= wptexturize(wpautop($piece));
		}
	}

	return $new_content;
}
remove_filter('the_content', 'wpautop');
remove_filter('the_content', 'wptexturize');

add_filter('the_content', 'raw_formatter', 99);
?>

Leave a Reply

Your email address will not be published. Required fields are marked *

*