How to use shortcodes in template files

You can use shortcodes in template files. To do this you should use a special WordPress function do_shortcode().

Simple example of use

This is the simplest example of using do_shortcode() function.

echo do_shortcode( '[gallery]' );

Shortcodes with attributes

do_shortcode() function works with shortcode attributes.

Please note the different quotation marks ("double" and 'single') used for the line with shortcode and for the shortcode attribute's meaning. Example of shortcode with attributes:

echo do_shortcode( '[gallery ids="1, 2, 3"]' );

Use of variables

You can write shortcodes to the variable before calling do_shortcode() function. Here are some examples:

$content = 'Hello';
$my_shortcode = '[box]' . $content . '[/box]';
echo do_shortcode( $my_shortcode );
$template = '[box color="%s"] %s [/box]';
$color = '#ffcc00';
$content = 'Hello';
$my_shortcode = sprintf( $template, $color, $content );
echo do_shortcode( $my_shortcode );

Nested shortcodes

  do_shortcode() function allows you to use nested shortcodes as well. Here are some examples:

echo do_shortcode( '[box] Hello, [username] [/box]' );
$content = 'Hello, [username]';
$shortcode = '[box]' . $content . '[/box]';
echo do_shortcode( $shortcode );

Important: make sure that opening and closing shortcode tags are used within a single do_shortcode() call. See examples below.

// This code WILL NOT work
echo do_shortcode( '[su_box]' );
echo do_shortcode( '[/su_box]' );

// This code WILL work
$my_shortcode = '[su_box]';
$my_shortcode .= '[/su_box]';
echo do_shortcode( $my_shortcode );