Differentiating between P tags wrapping images and P tags wrapping text nodes in WordPress?

I need a good solution to be able to style <p> tags differently in a wordpress post. More specifically I need to differentiate between paragraphs and images. WordPress just wraps all new lines in <P> tags.

Here are some possibilities:

Read More
  • Strip all <p> tags and add <P> tags where appropriate (around text)
  • Add a class on <P> tags that wrap text
  • Somehow differentiate between them as is (p img does not work.. I need to select the p tags that have a img child… I’d rather not use selectors that don’t work in IE 6)
  • Other solutions?

I do not want blog contributors to have to do something manually (add div tags), I want this done in the background.

I know other people are having problems with this. Please let me know your thoughts!

Thanks all,
Matt Mueller

Related posts

Leave a Reply

3 comments

  1. You could create a content filter function something like the below in your theme’s functions.php file or in a plugin. Note that this will add a class to any paragraph in the post body which has an image as it’s first child element (providing no text comes first), which may not be the exact behaviour you want.

    function my_content_filter($content) {
        return preg_replace('|<p>(<img[^<]*)</p>|i', '<p class="foo">${1}</p>', $content);
    }
    add_filter('the_content', 'my_content_filter');
    
  2. function format_content($content) {
        $contentArr = explode("n", $content);
        $output = "";
        foreach ($contentArr as $entity) {
            $entity = trim($entity);
            $numChars = strlen($entity);
            if(substr($entity, 0, 1) != "<" && substr($entity, $numChars-1) != ">" && $numChars > 0)
                $entity = '<p>'.$entity.'</p>';
            $output .= $entity;
        }
        return $output;
    }
    

    I’m sure I’ll run into some corner cases but this works pretty well for the time being.. It uses get_the_content() to prevent p tags from being added, then it passes the content to this function, which wraps stray text that doesn’t start with a tag in p tags, then returns.