Getting rid of the pesky WordPress <p> tags

While working on the site I encountered a unique problem with WordPress. When I inserted images, they were automatically wrapped in a <p> tag. This caused styling issues with my custom template. I needed to find a way to either:

  1. Remove the <p> tags
  2. Set the only the <p> tags margins equal to zero.

After some Google research, I discovered a nice plugin to remove the <p> tags. It disabled the wpautop function and removed the pesky <p> tags. Unfortunately, this targeted all my <p> tags, not just the ones causing issues with my <img>. This forced me to leave the <p> tags and look for another option.

What I needed was a way to style every <p> that contained an <img>. Enter my savior, jQuery. jQuery has the ability to do ascendant CSS styling. Meaning, you can target and style the parent by selecting it’s child.

This is all accomplished using jQuery’s :has selector. It looks for one element that “has” another in it. Here is what your <script> will look like.

<script>
$(document).ready(function(){
$("p:has(img)").css('margin' , '0');
});
</script>

In the above case I was selecting <p> that contains an <img>. I then set the margins equal to zero using the .css method. Kind of scary how simple it is huh?

For more info on how to implement jQuery check out this link.
http://docs.jquery.com/How_jQuery_Works#jQuery:_The_Basics

To find out more info check out this link.
http://docs.jquery.com/Selectors/has#selector

Before and after screenshots of using jQuery on my site. Notice the extra default margin wrapped around my image?

On the left, a screen shot of the extra margin created automatically by WordPress. On the right, is a screenshot after applying jQuery and some simple CSS styling.

UPDATE: The above jQuery technique is great for selecting elements based on their contents. However, if you are specifically interested in permanently removing the <p> that wrap <img> in WordPress, I suggest using a WordPress filter as opposed to jQuery. The filter will actually remove the <p> instead of merely removing its margins. Check out the following link.
http://snipplr.com/view/62087/