WordPress Tutorial: Replace HTML Tags within the Content

Sure, I can think of at least half a dozen other things to blog about when it comes to WordPress right now, but I can’t pass this up.

Earlier today I ventured on the WordPress.org Help Forums. Since I am no where near efficient in writing PHP code for core, I figure I could lend a hand to those support threads that don’t get touched. Here is the backstory:

User has moved their entries from Blogger into WordPress. For some reason instead of using paragraph tags, this user has been using Div tags. The user’s posts are coming out all funky with spacing being an issue. What can be done?

At first glanced I wondered if by just editing each post by removing the Div tags could solve the problem. There are too many posts. What else can we do? Create functions!

I found this support post where line breaks were needing to be replaced by paragraph tags. That seemed to work, so I made some posts using Div tags in a local install and went to work.

What we need to do first is to convert all the div tags in the_content() to paragraph tags.

1
2
3
4
5
// Replaces all <div> in the_content with <p>
function clear_replacedivopen($content){
	return str_replace("<div>","<p>", $content);
}
add_filter('the_content', 'clear_replacedivopen');

Second we need also need to convert all closing div tags to closing paragraph tags.

1
2
3
4
5
// Replaces all </div> in the_content with </p>
function clear_replacedivclose($content){
	return str_replace("</div>","</p>", $content);
}
add_filter('the_content', 'clear_replacedivclose');

And finally clean up any empty paragraph tags left.

1
2
3
4
5
// Clears all empty <p></p> in the_content()
function clear_emptyp($content){
	return str_replace("<p></p>","", $content);
}
add_filter('the_content', 'clear_emptyp');

Now we have a formatted page!

Share and Enjoy:
  • Print
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks

Got something to say? Go for it!