Using shortcodes in template files

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

Table of contents

  1. Simple example of use
  2. Shortcodes with attributes 
  3. Use of variables 
  4. Nested shortcodes

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 );
$color = '#ffcc00';
$content = 'Hello';
echo do_shortcode( '[box color="{$color}"] {$content} [/box]' );

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 WON'T work
echo do_shortcode( '[su_box]' );
echo do_shortcode( '[/su_box]' );

// This code WILL work
$my_shortcode = '[su_box]';
$my_shortcode .= 'Box content';
$my_shortcode .= '[/su_box]';
echo do_shortcode( $my_shortcode );
­čĄŁ Thank you!