Automatically remove code mistakes in wordpress posts

December 11, 2008 · Print This Article

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.

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).


Your choice for site templates and wordpress themes

Comments

Got something to say?

You must be logged in to post a comment.