简体   繁体   中英

Nesting shortcodes in Wordpress results in the inner shortcode not printing out at all

I've installed the _s theme and have barely begun to work on it.

I am trying to nest a shortcode named " b " inside a shortcode named " cb. " Here's my code (from the functions.php file):

// Short Code
function box_shortcode( $atts, $content = null ) {
  extract(
      shortcode_atts(array(
          's' => '1'
          ), $atts));

  if($s == '1') { $box_classes = 'c1_4 aside'; }
  if($s == '2') { $box_classes = 'c2_4 main'; }
  if($s == '3') { $box_classes = 'c3_4'; }
  if($s == '4') { $box_classes = 'c4_4'; }

  return '<section class="' . $box_classes . '">' . $content . '</section>';
}
add_shortcode( 'b', 'box_shortcode' );

function contentblock_shortcode( $content = null ) {
  return '<div class="inner">' . do_shortcode($content) . '</div>';
}
add_shortcode( 'cb', 'contentblock_shortcode' );

add_filter('the_content', 'do_shortcode');
add_filter('the_content', 'do_shortcode');

is not needed.

your both should take atts and content as attributes and your OUTER (not inner) function should have a do_shortcode inside it. Final code should be something like:

function box_shortcode( $atts, $content = null ) {
  extract(
      shortcode_atts(array(
          's' => '1'
          ), $atts));

  if($s == '1') { $box_classes = 'c1_4 aside'; }
  if($s == '2') { $box_classes = 'c2_4 main'; }
  if($s == '3') { $box_classes = 'c3_4'; }
  if($s == '4') { $box_classes = 'c4_4'; }

  return '<section class="' . $box_classes . '">' . $content . '</section>';
}
add_shortcode( 'b', 'box_shortcode' );

function contentblock_shortcode( $atts, $content = null ) {
  return '<div class="inner">' . do_shortcode($content) . '</div>';
}
add_shortcode( 'cb', 'contentblock_shortcode' );

If you will use your shortcodes as [cb][b]content[/b][/cb] If you'd like to use them the other way around, move do_shortcode($content) to the function box_shortcode( $atts, $content = null )

I believe that the problem is your contentblock_shortcode function takes $content as its first argument whereas it should take $atts first. Changing it to function contentblock_shortcode($atts, $content = null) should allow the inner do_shortcode to pass only the content on to the do_shortcode method within the inner section.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM