Shortcodes are specially formatted pieces of text that can be used to insert dynamic output into your posts, pages, widgets, and other static content areas.
Shortcodes come in three main flavors:
- A single shortcode like [myshortcode]
- Shortcodes with attributes like [myshortcode id=”1″ type=”text”]
- Enclosing shortcodes like [myshortcode id=”1″] … some content here … [/myshortcode]
The basics of creating shortcodes is to define the callback function for your shortcode using the add_shortcode() function. Any attributes are added to an array that is passed to the callback as the first $atts parameter. Any enclosed content is passed to the callback as the second $content parameter.
The next code creates a shortcode called msg and makes use of attributes and enclosed content:
shortcode callback for [msg] shortcode
Example: [msg type="error"]This is an error message.[/msg]
<div class="message message-error">
<p>This is an error message.</p>
function sp_msg_shortcode($atts, $content)
extract( shortcode_atts( array(
'type' => 'information',
), $atts ) );
$content = do_shortcode($content);
//allow nested shortcodes
$r = '<div class="message message-' .
$type . '"><p>' . $content . '</p></div>';
Notice that the content you want displayed is returned from the callback function rather than echoed to the output buffer. This is because the shortcode filter is typically run before any content has been pushed to the screen. If there were any echo calls inside this function, the output would show up at the top of the page instead of inline where you want it.