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:
- 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 wo开发者_开发问答rk.. 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
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');
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.
What about a simple plugin that utilizes jQuery's unwrap? http://wordpress.org/extend/plugins/unwrap-images/
DISCLAIMER: I did develop this plugin for my own needs.
精彩评论