Skip to content

WordPress – Create Nestable Shortcodes

Occasionally you might want to nest shortcodes inside each other. Consider the following example:

[eg-product]
[eg-option label="3 Day Ticket" price="550"]
[eg-option label="1 Day Ticket" price="225"]
[/eg-product] 

Here is the example

/*
 * This function generates a shortcode that provides wrapper code for the nested shortcode
 */ 
function eg_product($atts, $content=null) {
 
    $form   =  '<form method="post" action="">';
 
    // Assume we want to add incremental numbers in this example
    $form   .= '<input type="number" size="5" min="1" name="quantity" value="1" />';
    $form   .= '<select name="product">';
 
    // Need to apply_filters on the nested shortcode so that WordPress knows to parse shortcode as shortcode
    $form   .= apply_filters('the_content', $content);
    $form   .= '</select>';
    $form   .= '</form>';
 
    return $form;
 
}
 
add_shortcode( 'eg-product', 'eg_product' );
 
 
/*
 * This function generates the shortcode that will be parsed inside the eg-product shortcode
 */ 
function eg_option($atts, $content=null) {
 
    // Attributes added by shortcode
    $atts = shortcode_atts( array(
        'label'     => '',
        'price'     => ''
    ), $atts, 'eg-option' );
 
    // Output shortcode content
    return '<option value='.$atts['price'].'>'.$atts['label'].'</option>';
}
 
add_shortcode( 'eg-option', 'eg_option' );

Output

About 

10 years + experience in web development working with lots of different technology.

Published inPHPWordPress

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *