WordPress shortcodes

First, create a function with $atts as an argument. It holds all the attributes you create in the shortcode.

Simple shortcode

function foobar_func( $atts ){
  return "foo and bar";
add_shortcode( 'foobar', 'foobar_func' );

The shortcode to be used:


Shortcode with attributes

function bartag_func( $atts ) {
  $a = shortcode_atts( array(
    'foo' => 'something', // 'something' is default value
    'bar' => 'something else', // 'something else' is default value
  ), $atts );
  return "foo = {$a['foo']}";
add_shortcode( 'bartag', 'bartag_func' );

The shortcode to be used:

[bartag foo="value" bar="other value"]

Enclosing shortcode

Enclosing shortcodes need not only the $atts argument but a $content argument. This argument is what is enclosed by the shortcode. Use $content = null so it will work even if there’s no content.

function caption_shortcode( $atts, $content = null ) {
  return '<span class="caption">' . $content . '</span>';
add_shortcode( 'captions', 'caption_shortcode' );

Example shortcut:

[captions]My Caption[/captions]


<span class="caption">My Caption</span>