Introduction
Enclosing shortcodes let you wrap content inside special tags to add extra features or styles easily.
Enclosing shortcodes let you wrap content inside special tags to add extra features or styles easily.
[shortcode]Your content here[/shortcode]
[highlight]This text will be highlighted[/highlight]
[box color="blue"]This is inside a blue box[/box]
This code creates a shortcode named box that wraps content in a colored border box. You can set the color with an attribute. The content inside the shortcode is processed and displayed inside the box.
<?php // Register enclosing shortcode 'box' function box_shortcode($atts, $content = null) { $atts = shortcode_atts(array( 'color' => 'yellow' ), $atts, 'box'); return '<div style="border: 2px solid ' . esc_attr($atts['color']) . '; padding: 10px;">' . do_shortcode($content) . '</div>'; } add_shortcode('box', 'box_shortcode'); // Usage in post content: // [box color="red"]This text is inside a red box[/box] ?>
Always use do_shortcode() inside your shortcode function to process nested shortcodes.
Use shortcode_atts() to set default attribute values safely.
Enclosing shortcodes wrap content between opening and closing tags.
They let you add styles or features around blocks of text or other content.
Attributes customize how the shortcode works and looks.
box with content inside?[box]Content here[/box] correctly shows [box]Content here[/box]. Other options are either self-closing or invalid.[highlight color="yellow"]Important text[/highlight], what will be the expected behavior?[frame]Content here[frame][alert type="error"] that wraps content and shows it with a red background. Which is the best way to write the enclosing shortcode usage?[alert type="error"]Warning![/alert] correctly uses [alert type="error"]Warning![/alert]. [alert type="error" /]Warning! is self-closing and incorrect for enclosing content. [alert]Warning![/alert type="error"] misplaces attribute in closing tag. [alert type="error"]Warning! has incorrect closing tag syntax.Pass the test and this pattern moves unknown