WordPress removing tags?

I’d already come across a case where WordPress added <p> tags. However now I’m dealing with the opposite situation. When I add [] shortcodes inside <p> tags WordPress automatically removes <p> tags.

<p>[anyshortcode]Hello World[/anyshortcode]</p>

Becomes:

Read More
Hello World

Adding dir=”ltr” to <p> tags seems to fix the issue, maybe there is a way to add it programatically to all <p> tags?

Any ideas on how to fix this?

Related posts

Leave a Reply

5 comments

  1. This is pretty much what Foxsk8 mentioned in a comment, so credit should go to him, but these additional instructions will be useful. The WordPress plugin called TinyMCE Advanced will solve your problem.

    This plugin comes with an option inside Settings > TinyMCE Advanced that will fix your disappearing <p> tags. Mark the checkbox labeled Stop removing the <p> and <br /> tags when saving and show them in the Text editor and your <p> tags will be preserved.

  2. TinyMCE is programmed to make editing easy (which for us HTML savvy is often not the case). By default is should not accept <p> tagging around [BLOCKS]. That is because “[]” are used for shortcode not only in WP but a ton of PHP based CMSs. The shortcodes should have the appropriate content wrapper.

    Meaning the solution is to add the <p> tags in your shortcode code so that your content is wrapped the way you want.

  3. As an additional to Foxsk8 and E. Serrano. If post contains <p> around shortcodes, WP will still remove it. It does it in shortcode_unautop filter that is added in ‘wp-includesdefault-filters.php’. It ensures that shortcodes are not wrapped in <p>...</p>.

    So, we need to remove them:

    remove_filter( 'the_content', 'shortcode_unautop' );
    
  4. You can add this below code in your function.php file

    function content_formatter($content){
    
        $new_content = '';
        $pattern_full = '{([raw].*?[/raw])}is';
        $pattern_contents = '{[raw](.*?)[/raw]}is';
        $pieces = preg_split($pattern_full, $content, -1, PREG_SPLIT_DELIM_CAPTURE);
    
        foreach ($pieces as $piece) {
                if (preg_match($pattern_contents, $piece, $matches)) {
                        $new_content .= $matches[1];
                } else {
                        $new_content .= wptexturize(wpautop($piece));
                }
        }
    
        $array = array(
                '<p>[' => '[',
                ']</p>' => ']',
                ']<br />' => ']'
        );
    
        $new_content = strtr($new_content, $array);
    
        return $new_content;
    

    }

    Now call this function whereever required like;

    <?php echo content_formatter( get_field('field_name') ); ?>