How to make WordPress use non-greedy shortcode parsing?

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 Comment