Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 68 ยท Shortcodes, Options and Admin Pages

Shortcodes

Learn how WordPress shortcodes work: add_shortcode, shortcode_atts, enclosed content, nesting, escaping output, do_shortcode and when to use blocks instead.

A shortcode is a tiny tag in square brackets that an author types into post content, such as [gallery] or [button url="/pricing"]Buy now[/button]. When WordPress prints the content, it replaces each tag with whatever your PHP callback returns. Shortcodes let a plugin or theme offer reusable output (a form, a price table, a list of events) to people who never touch code.

In this lesson you will register shortcodes, read their attributes safely, handle enclosed content, nest them, and escape what they print. Shortcodes are older than the block editor, but millions of sites still use them, and you will meet them in almost every legacy plugin. The hook system behind them is the one from Actions and Filters.

Registering a shortcode

You register a shortcode with add_shortcode( $tag, $callback ), usually from a plugin file or on the init hook. The callback receives three arguments and must return a string.

PHP
add_shortcode( 'greeting', 'nw_greeting_shortcode' );

function nw_greeting_shortcode( $atts, $content = null, $tag = '' ) {
	$atts = shortcode_atts(
		array(
			'name' => 'friend',
		),
		$atts,
		$tag
	);

	return '<p class="greeting">Hello, ' . esc_html( $atts['name'] ) . '!</p>';
}

With that in place, [greeting name="Ada"] in a post becomes the paragraph "Hello, Ada!".

Three rules matter right away:

  • Return, never echo. WordPress replaces the tag with the returned string. If you echo inside the callback, the output appears at the top of the page, before the content, not where the tag stood.
  • Prefix your tag. Shortcode names share one global list. A tag like [button] collides with other plugins, so real code uses something like [nw_button].
  • Tag names are limited. They may not contain spaces, square brackets, angle brackets, & or /. Stick to lowercase letters, digits and underscores.

WordPress runs do_shortcode() on post content through the the_content filter, so shortcodes work in the loop from The Loop without extra code. Text widgets and your own strings do not get this treatment automatically: call do_shortcode( $text ) yourself.

flowchart LR
    A["Post content<br/>with [greeting name=Ada]"] --> B["the_content filter"]
    B --> C["do_shortcode()"]
    C --> D["Find registered tags"]
    D --> E["Parse attributes"]
    E --> F["Call your callback"]
    F --> G["Replace tag with returned HTML"]

Shortcodes are expanded when the content passes through the the_content filter.

Attributes and shortcode_atts

Authors write attributes inside the opening tag: [greeting name="Ada" excited]. WordPress parses the text after the tag name and hands your callback an array. Three details surprise beginners:

  • Attribute names are lowercased. Name="Ada" arrives as name.
  • Values may use double quotes, single quotes or no quotes (when they contain no spaces).
  • A bare word with no = has no name, so it is stored under a numeric key: excited arrives as $atts[0].

Also, when a shortcode has no attributes at all, $atts is an empty string, not an empty array. That is why every callback should normalize it.

shortcode_atts( $defaults, $atts, $shortcode ) does that normalization. It returns an array containing exactly the keys from $defaults, using the author's value when present and the default otherwise. Any attribute the author typed that is not in your defaults is silently dropped. The third argument is the tag name; passing it lets other code adjust the result through the shortcode_atts_{$shortcode} filter.

The first TryIt reimplements the parsing and the defaults merge so you can see exactly how input text turns into an array. This is a stand-in written for this site, not WordPress code: real WordPress uses shortcode_parse_atts() with a more elaborate regular expression, but the rules above are the same.

PHP Parsing shortcode attributes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice what happens to excited and size in the last case: the parser keeps them, but the merge step drops them because they are not in the defaults. If you need a flag attribute, either read $atts[0] before merging or ask authors to write excited="yes", which is clearer anyway.

All attribute values are strings. limit="5" gives you "5", so cast with absint() or (int), and compare booleans against strings like "true" or "yes" yourself.

Enclosed content

A shortcode can wrap text: [box title="Heads up"]This is the body.[/box]. The text between the opening and closing tags is passed as the second argument, $content. For a self-closing tag such as [greeting name="Ada"], $content is null.

PHP
add_shortcode( 'nw_box', function ( $atts, $content = null ) {
	$atts = shortcode_atts( array( 'title' => '' ), $atts, 'nw_box' );

	$html  = '<aside class="nw-box">';
	if ( '' !== $atts['title'] ) {
		$html .= '<strong>' . esc_html( $atts['title'] ) . '</strong>';
	}
	$html .= wp_kses_post( do_shortcode( (string) $content ) );
	$html .= '</aside>';

	return $html;
} );

Two things to notice. First, the callback calls do_shortcode( $content ) itself. WordPress does not expand shortcodes inside enclosed content for you, because the callback might want the raw text. If you forget this call, nested tags show up literally. Second, the enclosed content is whatever the author typed, so it may contain HTML. Pass it through wp_kses_post() (or another suitable filter) if you did not write it yourself. You will study that function in Sanitizing and Validating Input.

Nesting and its limits

Nesting different shortcodes works: [nw_box][greeting name="Ada"][/nw_box] expands the greeting inside the box, because the box callback calls do_shortcode(). Nesting the same tag inside itself, such as a box inside a box, is not reliable. The parser matches the first closing tag it finds, so the outer box ends too early. If you need that, give the inner shortcode a different name.

Escaping output

A shortcode callback is a place where untrusted text meets HTML, so treat it like any template. Attribute values come from authors, and on many sites contributors can write posts, so assume hostile input:

  • Use esc_html() for text, esc_attr() for values inside HTML attributes and esc_url() for links.
  • Escape late, at the moment you build the string, not when you read the attribute.
  • Only the pieces you built are trusted. Enclosed content is not.

Authors can also show a shortcode literally, without running it, by doubling the brackets: [[greeting]] prints [greeting] in the page. The second TryIt builds a small runner with enclosures, nesting, unknown tags left alone, and the bracket escape.

PHP A shortcode runner with enclosures and escaping

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Look at three behaviors in the output. The <b>Bob</b> value is escaped to harmless text because the callback calls esc_html(). The [unknown] tag is left exactly as typed, since nothing is registered under that name. And [[greeting]] loses one pair of brackets instead of running.

Handy helper functions

Real WordPress ships a few functions around the shortcode list:

Function Purpose
shortcode_exists( $tag ) Is this tag registered?
has_shortcode( $content, $tag ) Does this text contain a use of the tag? Useful for loading CSS or JS only on pages that need it.
remove_shortcode( $tag ) Unregister one tag.
strip_shortcodes( $content ) Delete all registered shortcodes from a string, as excerpts do.
do_shortcode( $content ) Expand every registered shortcode in a string.

A very common pattern is to enqueue a stylesheet only when the post uses your shortcode:

PHP
add_action( 'wp_enqueue_scripts', function () {
	global $post;
	if ( $post instanceof WP_Post && has_shortcode( $post->post_content, 'nw_box' ) ) {
		wp_enqueue_style( 'nw-box', plugins_url( 'box.css', __FILE__ ), array(), '1.0.0' );
	}
} );

This misses shortcodes that sit in widgets or in other posts, so it is a good default, not a guarantee.

Shortcodes or blocks?

On a block-editor site, new features are usually better as blocks (see Building Blocks: An Overview and Dynamic Blocks and Block Bindings). Blocks show a live preview in the editor, have structured, typed attributes and need no square-bracket syntax. Shortcodes still make sense when:

  • you must stay compatible with existing content or a classic-editor workflow,
  • you need output inside a place that only accepts text, such as a widget or a custom field,
  • you are writing something quick for a site you control.

WordPress also has a Shortcode block, so existing shortcodes keep working in the block editor. What you will not get is a visual preview unless you build one.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where should a shortcode callback put the HTML it produces?

    WordPress replaces the tag with the callback's return value. Echoing prints at the wrong place, usually before the post content.
  2. 2. A shortcode is written as [box title="Hi"]text[/box]. Which callback argument holds the word text?

    The text between the opening and closing tags is the second argument, conventionally named $content. $atts holds the attributes and $tag the tag name.
  3. 3. What does shortcode_atts() do with an attribute the author typed that is not in the defaults array?

    The result contains exactly the keys listed in the defaults. Unknown attributes are discarded, so read them before merging if you need them.
  4. 4. Why does a box shortcode need to call do_shortcode() on its $content?

    Enclosed content is passed to your callback as raw text. Calling do_shortcode() on it expands any nested tags. It does not escape anything.

Summary

  • add_shortcode( $tag, $callback ) registers a tag; the callback gets $atts, $content and $tag, and must return a string.
  • Attributes arrive as strings with lowercased names; flag words get numeric keys, and an empty tag gives an empty string, so normalize with shortcode_atts().
  • Enclosed content is not expanded automatically: call do_shortcode() on it, and filter it if you did not write it.
  • Escape every attribute value you print (esc_html(), esc_attr(), esc_url()).
  • [[tag]] prints the tag literally; unknown tags are left alone; the same tag cannot be nested in itself.
  • Prefer blocks for new features; keep shortcodes for legacy content and text-only places.

Next, learn where plugins keep their settings: The Options API and Transients.