Support » Fixing WordPress » Prevent WordPress from wrapping tags with P and BRs

  • Resolved Ihor Vorotnov

    (@headonfire)


    While building a new theme I found that WordPress wraps all <samp></samp> tags with <p></p>. According to specs, <samp> represents (sample) output from a program or computing system. It’s not a block-level element, it can be used inline, as well as <kbd>, <var> or <code>.

    The problem is WordPress wraps this tag with paragraph. I managed to solve this issue with this code:

    function righter_filter_ptags($content) {
        $content = preg_replace('/<p>\s*(<a>)?\s*(<img .* \/>)\s*(<\/a>)?\s*<\/p>/iU', '\1\2\3', $content);
        $content = preg_replace('/<p>\s*(<iframe .*>*.<\/iframe>)\s*<\/p>/iU', '\1', $content);
        $content = preg_replace('/<p>\s*(<samp .*>*.<\/samp>)\s*<\/p>/iU', '\1', $content);
        return $content;
    }
    add_filter('the_content', 'righter_filter_ptags');
    </a>

    It actually strips Ps from images and iframes as well. While it gives the expected results – all <img>, <iframe> and <samp> tags now have no wrapping paragraphs, WordPress now adds <br> tag before <samp>. I’m working in ‘Text’ mode and writing everything in one line, with no line breaks. Here’s the sample code:

    We have not only <code>code</code> tag, but also <kbd>kbd</kbd> and <samp>samp</samp> tags.

    and here’s sample output in html source code on the website:

    <p>
        We have not only
        <code>code</code>
        tag, but also
        <kbd>kbd</kbd>
        and
        <br>
        <samp>samp</samp>
        tags.
    </p>

    It looks exactly this, with all line-breaks. Everything is fine except this <br> tag right before <samp>. Any ideas how to remove it? Did a lot of googling, no result.

Viewing 3 replies - 1 through 3 (of 3 total)
  • Just noticed another problem. It not only adds unnecessary <br> right before <samp>, but also wraps any content after the <samp> into another paragraph. In my case the part ‘tags.’ gets wrapped into new paragraph and I definitely don’t want it.

    Ok, it’s a TinyMCE bug. Had to spend few more hours on this to figure out…

    For some reason, TinyMCE defines a <samp> tag as a block-level element, which is definitely wrong.

    There is a WordPress Trac ticket [18807] for this bug and it’s fixed now, seems to be rolled out with WordPress 3.6 update. Patching my WP sources for now and waiting for 3.6 update.

    Ok, it’s a TinyMCE bug. Had to spend few more hours on this to figure out…

    For some reason, TinyMCE defines a <samp> tag as a block-level element, which is definitely wrong.

    There is a WordPress Trac ticket [18807] for this bug and it’s fixed now, seems to be rolled out with WordPress 3.6 update. Patching my WP sources for now and waiting for 3.6 update.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Prevent WordPress from wrapping tags with P and BRs’ is closed to new replies.