Nesting Shortcodes in WordPress (shortcodes in shortcodes)

Shortcodes in WordPress that are available in are extreamly usefull for applying formatting or embeding external content in your pages or posts.
The only problem with them is the parser only does a single pass on the content, so if your shortcodes outputs a shortcode, or you have a shortcode nested within shortcodes, they wont render.

I found on the WordPress Codex that, to enable nesting shortcodes, or shortcodes within shortcodes, I would have to add return do_shortcode($content); This way it will push the result back into the parser.

That’s all very well, but what of shortcodes I didn’t make, or don’t have this added to them? So I made a little plugin that would override the default do_shortcode filter with an evaluator that would check for shortcodes and keep pushing it to do_shortcode until they are all done.

Plugin Name: Shortcode Recursion
Description: Adds shortcode recursion for shortcodes that have shortcodes in shortcodes that has a shortcode in a shortcode in a shortcode with a shortcode in it, all wrapped in a shortcode within a shortcode... and so on.
Author: David Cramer
Version: 1.0
Author URI:

/* evaluates content for shortcodes and sends it to do_shortcode() if needed and revaluates the result */
function shortcode_inception($content){
    // evaluate content for shortcodes.
    preg_match_all("/".get_shortcode_regex()."/s", $content, $matches);
    // if has shortcode, return revaluated content from  native do_shortcode
        return shortcode_inception(do_shortcode($content));
    // return if nothing is found
    return $content;
// remove the native do_shortcode filter
remove_filter('the_content', 'do_shortcode', 11);
// replace the filter with the evaluator function
add_filter('the_content', 'shortcode_inception', 11);  

Leave a Reply

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

%d bloggers like this: