简体   繁体   中英

How do you get attributes in a nested shortcode?

I am creating a slideshow shortcode for my Wordpress theme, but have run into a small issue. This is what the shortcode looks like:

[slideshow width=500]
    [slide]http://example.com/image1.jpg[/slide]
    [slide]http://example.com/image2.jpg[/slide]
    [slide]http://example.com/image3.jpg[/slide]
[/slideshow]

So, basically it is two different shortcodes (slideshow and slide), I need to set the width of each "slide" shortcode. How do I get the "width" attribute from the parent "slideshow" shortcode and pass it to each child "slide"?

    //Create slideshow wrapper div
    function shortcode_slideshow($atts, $content = null){  
        $return = '<div class="slideshow">';
        $return .= do_shortcode($content); 
        $return .= '</div><!-- end slideshow -->'; 

        return $return; 
    } 

    //Create each slide HTML 
    function shortcode_slide($atts, $content = null){
        $return = '<a class="dolightbox" href="'.$content.'">'; 
        $return .= '<img src="'.$content.'" /></a>'; 
        return $return; 
    }

    add_shortcode('slideshow', 'shortcode_slideshow');
    add_shortcode('slide', 'shortcode_slide');

Ended up using global vars to pass the value into the second shortcode function. I thought maybe there was a native Wordpress method of doing it, but I apparently not.

//Create slideshow wrapper div
$globalWidth = NULL; 

function shortcode_slideshow($atts, $content = null){ 
    extract(shortcode_atts( array('width' => ''), $atts));
    global $globalWidth;
    $return = '<div class="slideshow">';
    $return .= do_shortcode($content); 
    $return .= '</div><!-- end slideshow -->'; 

    return $return; 
} 

//Create each slide HTML 
function shortcode_slide($atts, $content = null){
    global $globalWidth;
    $return = '<img width="'.$globalWidth.'" src="'.$content.'" />'; 

    return $return; 
}

add_shortcode('slideshow', 'shortcode_slideshow');
add_shortcode('slide', 'shortcode_slide');

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