1

I'm trying to use nested shortcodes, but i'm having problems with it.

Everytime i try to nest two shortcodes created by me...

First declared in functions.php (the inner):

function p_generic_shortcode( $atts , $content = null )
{
    return '<p class="pov generic">' . do_shortcode($content) . '</p>';
}
add_shortcode( 'pov-generic', 'p_generic_shortcode' );

Second declared in functions.php (the outer):

function f_girl_shortcode( $atts , $content = null )
{
    return '<p class="talk girl">' . do_shortcode($content) . '</p>';
}
add_shortcode( 'talk-girl', 'f_girl_shortcode' );

When i enter the following code in bbpress editor:

[talk-girl]TEXT[pov-generic]OTHER TEXT[/pov-generic][/talk-girl]

It outputs the follow code:

<p class="talk girl">TEXT</p>
<p class="pov generic">OTHER TEXT</p>

And not as i expected:

<p class="talk girl">TEXT<p class="pov generic">OTHER TEXT</p></p>
1

Use Output buffering for the best result of shortcode, especially when you are outputting some HTML in it:

function f_girl_shortcode( $atts , $content = null )
{
    ob_start(); ?>
          <div class="talk girl"><?php echo do_shortcode($content); ?></div>
    <?php
    return ob_get_clean();
}
add_shortcode( 'talk-girl', 'f_girl_shortcode' );

and

function p_generic_shortcode( $atts , $content = null )
{
    ob_start(); ?>
          <div class="pov generic"><?php echo do_shortcode($content); ?></div>
    <?php
    return ob_get_clean();
}
add_shortcode( 'pov-generic', 'p_generic_shortcode' );

EDIT

Yes, block level element is not the issue, I found the issue is the <p> tag only. The <p> tag doesn't support another <p> tag or any block level element within (More here). So I changed my answer with <div> tags.

And another good practice, I tend to follow: the [talk-girl] is the parent, and the [pov-generic] is the child. In such case, I follow a simple rule: no child without a parent - so declare parent first, then the child - it may be nothing, but in some cases, it's many thing. I changed the position of the declaration of the code too. :)

Reference:

  • Still won't work. This output me <p class="talk girl">TEXT</p> <p class="pov generic">OTHER TEXT</p> Something that i realized: if i change the HTML tag for one of the shortcodes, it will print accordingly. But if the two shortcodes output a block element (div or p) it close the parent and the child is output after it. – Vico Apr 30 '15 at 0:23
  • @Vico you are right. Edited my answer now with the cause. – Mayeenul Islam Apr 30 '15 at 3:50
  • SOLVED! I just put the pov-generic shortcode (the only can go as a child in my system) in a span element. Worked flawlessly an even wordpress enclose the non-child shortcode with a p. Thank you so much for the answer!! – Vico Apr 30 '15 at 9:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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