I’d like to stop WP from wrapping <p> tags around <div> tags in the TineMCE editor …

Here’s what I’ve got:

function filter_ptags_on_images($content) {
    return preg_replace('/<p>([^>]*)<\/p>/i', '$1', $content);

add_filter('the_content', 'filter_ptags_on_images');

That removes all <p> tags around text but nothing that is wrapped in <p><div>text</div></p>.

I’d also like to know a solution if I have nested <div> tags like <p><div><div>text</div></div></p>.


Greedy and Ungreedy modifier:

preg_replace( '/<p>(.+)<\/p>/Uuis', '$1', $content );

Tested with this script:

$c = array();
$c[] = '<p>text</p>';
$c[] = '<p><div>text</div></p>';
$c[] = '<p><div><div>text</div></div></p>';

foreach ( $c as $content ) {
    $e = preg_replace( '/<p>(.+)<\/p>/Uuis', '$1', $content );
    var_dump( $e );

Also try remove_filter( 'the_content', 'wpautop' );

  • Thanks for that! I’m afraid I forgot to mention, that I don’t want the <p> tags around text only shall not be removed—only the ones before <div> tags. – user1706680 Jan 21 '13 at 9:10
  • preg_replace('/<p>((<div([^>]*)>)(.+)(<\/div>))<\/p>/iU', '$1', $content); works for me. Is that correct? What does this Uuis at the end of the string mean? – user1706680 Jan 21 '13 at 9:30
  • The first line of my answer is a link to the PCRE pattern modifiers. The u modifier (lowercase u) treat the pattern as utf-8. This modifier should be used even when the pattern does not contain any utf-8 characters. If you always use this modifier, you don't get into trouble when the pattern contains utf-8 characters. The s modifier should be used because the content can contain linebreaks. – Ralf912 Jan 21 '13 at 12:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.