I have created a shortcode to output a wp_Query. Nowhere in my query do I output any <p></p> paragraph marks. However the widget puts this before my output and after.

At first I thought maybe it was something in my code, but I created this sample version as an example:

function test_shortcode() {
    $testout="<div>hi there.</div>";
    return $testout;
}
add_shortcode ('show-test', 'test_shortcode');

I then output the shortcode in my footer widget. I’m using wordpress 5.9 and the widgets are now gutenberg. I’ve tried using the shortcode block and the custom-html block.

[show-test]

This is what I expect for an output:

<div>hi there.</div>

But this is what I receive:

<p></p><div>hi there.</div><p></p>

UPDATE:
For completion sake, this is the FULL widget output:

<div class="footer-widget-2">
        <aside id="block-10" class="widget inner-padding widget_block"><p></p><div>Hi there.</div><p></p>
    </aside>
</div>

I’ve tried changing themes this still happens. Does anyone have any idea what is causing the extra paragraph marks before and after? More importantly how to stop them?

1 Answer
1

Does anyone have any idea what is causing the extra paragraph marks before and after?

The Shortcode block performs wpautop() on the content (in the block) before the shortcode is parsed (see source on GitHub), i.e. wpautop( '[show-test]' ) in your case, which then returns <p>[show-test]</p> and then outputs <p><div>hi there.</div></p> after the shortcode is parsed.

So I believe that was the raw (or server-generated) code that you could find in the page source (Ctrl+U on Chrome Windows desktop), but because the nesting/markup is invalid (a div can not be in a p), then the browser automatically fixed the nesting which became this instead: <p></p><div>hi there.</div><p></p>, i.e. two empty paragraphs were added outside the div element.

And with that said, you were likely viewing the DOM tree and not the raw HTML source, hence you didn’t notice the actual HTML outputted via the Shortcode block.

For more information on DOM vs. page/HTML source, check these out:

  • What is the difference between HTML and DOM? on Medium

  • What is the difference between source code and DOM? on Stack Overflow


More importantly how to stop them?

The Shortcode block doesn’t have any setting that would stop/disable the auto-P-ing, and while it’s possible to override the render_callback for the block, or code your own block/widget, there’s actually a very easy option to prevent the issue from happening, which is — add your shortcode using the Custom HTML block instead of the Shortcode block. 🙂

(If that is still giving you the same issue, then as I said in my comment, you can try clearing your site cache and disable caching for a while)

Leave a Reply

Your email address will not be published. Required fields are marked *