Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

Register a new shortcode handler depending on the attribute value:

function wrapper_shortcode_handler ( $atts, $content ) {

    if ( "apple" === $atts["snack"] )
        add_shortcode( "flavor", "healthy_callback" );

    if ( "donut" === $atts["snack"] )
        add_shortcode( "flavor", "fatty_callback" );

    return do_shortcode( $content );
}

See also Execute shortcode only in another shortcode

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.