Disable WordPress automatic formatting on posts using a shortcode

If you often display code snippets on your WordPress blog, you know how bad WordPress automatic formatting can be. Happilly, with the help from a very cool shortcode you can be able to disable it on a certain portion of text.

The first thing to do is to add the following function to your functions.php file:

function my_formatter($content) {
	$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 .= $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', 'my_formatter', 99);

Once done, you can use the [raw] shortcode in your posts:

[raw]Unformatted code[/raw]

If you're interested in WordPress shortcode, I'll be publishing a WordPress shortcodes related article on my blog Cats Who Code on thursday. Make sure you grabbed Cats Who Code RSS feed so you're not going to miss it!

Thanks to TheBinaryPenguin for this awesome shortcode!

Related Posts

17 Responses

Jun 22 2009 11:08

WoW! Great thing. Never thought about this before. Thank you.

Jun 22 2009 12:30

Just what I was looking for! Thanks a lot!

Jun 22 2009 17:54

Hi, Great tip. I use Wp-Codebox plugin for posting bash commands and most of the times Wordpress screws them.

Much appreciated!

Jun 23 2009 06:22

Great, Thanks for sharing.
I won’t miss the feed.

Jun 23 2009 10:27

Your code above doesn’t use the shortcode api – if it did, you wouldn’t need any of the regex or the variable parsing.

http://codex.wordpress.org/Shortcode_API

Jun 25 2009 02:40

I had to increase the priority to 1 on a site as some plugins content was being handled oddly.

Jul 05 2009 02:21

This is a fantastic little piece of code, thank you so much for sharing it! I was having problems with WP formatting another shortcode and my previous solution was to turn off the visual editor. I’m very glad to be able to turn the visual editor back on now. :)

Sep 14 2009 17:58

Hmm… Shortcodes are something I haven’t delved into properly yet but look very interesting!

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required