How to: Automatically remove code mistakes in posts

If you’re not good with XHTML, or if you’re running a multi-author blog with people which don’t know XHTML either, you’re probably upset with the amount of code mistakes that can be found in your posts code. Here’s a great piece of code to automatically remove code mistakes as such as empty <p>, inline style, etc.

To achieve this recipe, you first have to creat the function which will takes your post content, clean it and print or return it.
Copy the code below to the functions.php file from your theme. Create that file if it doesn't exists.

function clean_bad_content( $bPrint = false ){
	global $post;
	$szPostContent = $post->post_content;
	$szRemoveFilter = array( "~<p[^>]*>\s?</p>~", "~<a[^>]*>\s?</a>~", "~<font[^>]*>~", "~<\/font>~", "~style\=\"[^\"]*\"~", "~<span[^>]*>\s?</span>~" );
	$szPostContent = preg_replace( $szRemoveFilter, '' , $szPostContent);
	$szPostContent = apply_filters('the_content', $szPostContent);
	if ( $bPrint == false ) return $szPostContent; else echo $szPostContent;
}

Proceed as the following to display your clean post content:

<?php if ( function_exists( 'clean_bad_content' ) ) clean_bad_content( true ); ?>

The clean_bad_content() only takes one argument, a boolean to specify if you'd like to print the result (true) , or get it for further use in php (false).

Thanks to Matt Varone for this awesome function!

Related Posts

Related Posts

No related posts.

Leave a Comment

* Name, Email, Comment are Required