Suppose we have two different sets of nested shortcodes, like this:
Apple version
[wrapper snack="apple"] Today I had a [flavor] snack... [/wrapper]
- Desired output: My snack was quite HEALTHY today...
Donut Version
[wrapper snack="donut"] Today I had a [flavor] snack... [/wrapper]
- Desired output: My snack was quite FATTY today...
My question is: how can I parse the nested shortcode ([flavor]
) differently depending on the shortcode it's nested in (i.e., based on [wrapper]
's snack attribute)? Please accept for the sake of the question that it's impossible/impractical to add an attribute to [flavor]
.
In pseudo-code, it might work something like this:
function flavor_shortcode_handler ( $atts, $content ) {
$wrapper = ??? // The value of the shortcode this is nested inside
if ( $wrapper == 'apple' ) return 'HEALTHY';
if ( $wrapper == 'donut' ) return 'FATTY';
}
I imagine there are a variety of ways to get the same effect by how we write wrapper
's handler function.
Idea 1: Use a global variable
function wrapper_shortcode_handler ( $atts, $content ) {
// After extracting the snack attribute...
$GLOBALS['wrapper_value'] = $snack;
return do_shortcode( $content );
}
Idea 2: Find/replace the nested shortcode before processing it
function wrapper_shortcode_handler ( $atts, $content ) {
// After extracting the snack attribute...
$new_content = str_replace( '[flavor]', '[flavor wrapper="'.$snack.'"]', $content );
return do_shortcode( $new_content );
}
Obviously the examples and solutions are oversimplified, but is there an alternative that would work better?