I made a plugin that adds a shortcode with optional content. If there’s no content, WordPress still tries looking for a closing tag. This is clearer with an example:

[span class="foo"]
[span class="bar"]
[span class="baz"]stuff[/span]

Wanted:

<span class="foo"></span>
<span class="bar"></span>
<span class="baz">stuff</span>

Actual:

<span class="foo">
  [span class="bar"]
  [span class="baz"]stuff
</span>

Is there a way to make WordPress produce the first output? I’m expecting many of the plugin’s users to be confused by this behavior. One way is to modify the_content before do_shortcode runs, but it’s pretty hacky. Is there a clean or existing way to change this behavior?

Edit: I’m not asking why this behavior occurs, I’m asking for a good way to change this behavior.

2 Answers
2

WordPress interpreted your shortcode like this:

Wordpress thought your shortcode like

The main issue being, that you have a unclosed shortcode of the same tag in front of an enclosing shortcode of the same tag, which won’t be parsed correctly. The documentation states that you might run into problems with unclosed shortcodes.

When you call your shortcode like this:

[span class="foo" /]
[span class="bar" /]
[span class="baz"]stuff[/span]

You will get your expected result.

Because the self-closing marker / is needed in your use-case, although it generally is considered optional, but as it forces the parser to ignore following closing tags it gets you your expected result.

The above solution is the correct usage of shortcodes according to the WordPress Shortcode API. If you want to to pre-process your shortcode in one way or another you can do that, but generally just make your users use the correct syntax in the first place.

Leave a Reply

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