Skip to content

Everything for WordPress, web development — and beyond

⚡ How to use WordPress shortcodes: complete guide

⚡ How to use WordPress shortcodes: complete guide

Picture this: you're adding a gallery of 20 images to an article. Without shortcodes, that's dozens of lines of HTML with wrappers, classes, data attributes, and thumbnail links. With a shortcode, it's one line: [gallery]. It was precisely for this contrast between routine volume and results that WordPress 2.5 introduced shortcodes, and nearly two decades later, the mechanism remains indispensable.

The problem is that most users either fear shortcodes as "programmer magic" or copy them blindly without understanding the syntax. Meanwhile, a single custom shortcode can replace a forty-megabyte plugin or save an hour of routine work per month. This breakdown, from built-in [gallery] and [audio] to your own shortcode in functions.php, will give you complete control over the tool.

💡 Quick overview:

  • What a shortcode is: a tag in square brackets that WordPress replaces with the result of a PHP function when loading a page.
  • Built-in shortcodes: gallery, audio, video, caption, embed, and playlist work right after installing WordPress, without plugins.
  • Shortcode parameters: key="value" syntax lets you customize output without changing code.
  • Creating your own shortcode: from a simple URL replacement to an image shortcode with attributes, ready PHP code for functions.php.
  • Shortcodes in widgets and templates: how to enable support with one line and where it comes in handy.

What a shortcode is and how it works

A shortcode is a brief tag in square brackets that WordPress replaces with the result of executing a PHP function at the moment a page is rendered. You write [gallery] in the editor, visitors see a neat grid of images. No magic: behind every shortcode stands a function registered via add_shortcode() in the core, theme, or plugin.

The key difference from static HTML inserts: a shortcode executes on the server side. You pass it parameters, and the result is generated dynamically. The content changes, the output changes, without manually editing dozens of pages.

From the editor's perspective, there's a nuance. The visual editor (Gutenberg or classic TinyMCE) immediately renders the shortcode as a preview, so to work with parameters and nested tags, switch to text mode. Only there can you see the real structure: opening tag, attributes, content, closing tag.

WordPress code editor on a computer screen

Built-in WordPress shortcodes: what's available without plugins

WordPress ships with six registered shortcodes. You don't need to enable or configure them, just insert them into a post and get results.

Shortcode

What it does

Example

[audio]

Inserts an audio file with a player

[audio src="podcast.mp3"]

[video]

Inserts a video file with a player

[video src="tutorial.mp4"]

[gallery]

Grid of gallery images

[gallery ids="1,5,7" size="medium"]

[caption]

Wraps content with a caption

[caption]Text[/caption]

[embed]

Embeds external content with size control

[embed width="600"]URL[/embed]

[playlist]

Collection of audio or video

[playlist type="video"]

The most flexible among them is [gallery]. The ids attribute lets you specify specific images by ID, even those not attached to the current post. The size attribute sets thumbnail size (thumbnail, medium, large, or full). The combination of these two parameters covers most scenarios for which people used to install a separate gallery plugin.

[audio] and [video] support multiple sources, the browser will pick a compatible format. Playlists via [playlist] are assembled from attachment IDs similar to a gallery, but output a player with track switching.

Shortcode parameters: how to control output

Most shortcodes accept attributes in key="value" format. Substituting values changes the function's logic without interfering with code.

Take [gallery]. Without parameters, it shows all post images in standard size. Add specifics:

1[gallery ids="12,34,56" size="large" columns="3"]

Now output is limited to three specified images, size is increased to large, and the grid is arranged in three columns. Parameters can be combined arbitrarily, those not specified receive default values.

Some shortcodes use opening and closing tags when content needs to be passed between them. Say, a Google Maps plugin might expect a construction like:

1[maps]New York, USA[/maps]

The closing tag always starts with a forward slash /. WordPress uses this notation to distinguish content between tags from attributes inside the opening tag.

How to create your own shortcode

When you've inserted the same URL, HTML block, or call-to-action into articles for the tenth time in a week, it's time to write a shortcode. This doesn't require being a PHP developer: the basic construction fits in three lines.

Simple shortcode for URL

Add this code to the end of your theme's functions.php file (Appearance → Theme Editor → functions.php):

1function techblog_short_url() {
2 return 'https://techblog.sdstudio.top';
3}
4add_shortcode( 'techblog', 'techblog_short_url' );

Now in any post, [techblog] will automatically be replaced with the site URL. The function returns a string, WordPress substitutes it in place of the shortcode.

Two critically important rules from the official documentation:

  • The function returns a value via return, not outputs via echo. Direct output breaks rendering order and leads to unexpected results.
  • Register shortcodes on the init hook so WordPress has time to load all dependencies:
1add_action( 'init', 'techblog_register_shortcodes' );
2function techblog_register_shortcodes() {
3 add_shortcode( 'techblog', 'techblog_short_url' );
4}

Shortcode for image with customizable attributes

A slightly more complex scenario: you want to insert an image, setting width and height directly in the editor. In functions.php:

1function techblog_img_shortcode( $atts, $content = null ) {
2 $atts = shortcode_atts(
3 array(
4 'width' => '',
5 'height' => '',
6 ),
7 $atts,
8 'img'
9 );
10 return '<img src="' . esc_url( $content ) . '" width="' . esc_attr( $atts['width'] ) . '" height="' . esc_attr( $atts['height'] ) . '" alt="" />';
11}
12add_shortcode( 'img', 'techblog_img_shortcode' );

Usage in the editor:

1[img width="800" height="600"]https://example.com/photo.jpg[/img]

The shortcode_atts() function merges passed attributes with default values, this is the standard and safe way to handle parameters. Note esc_url() and esc_attr(): escaping is mandatory when outputting user input on the frontend. A full list of available image attributes is in the W3C specification.

Separately worth mentioning is attribute validation. When you accept values from the editor and insert them into HTML, always check data types. For numeric attributes like width and height, use intval(), this will cut off accidental letters. For strings, set an allowed set of values via in_array(), for example thumbnail sizes (thumbnail, medium, large). This way the layout stays intact, and frontend results will be predictable, even if the author makes a mistake in the attribute value.

Shortcodes in text widgets and PHP files

Since WordPress version 4.9 (November 2017), shortcodes automatically work in text widgets. But if you're using a custom theme without built-in support, you can enable it with one line in functions.php:

1add_filter( 'widget_text', 'do_shortcode' );

To avoid automatic insertion of <p> and <br> tags around the shortcode in a widget (WordPress auto-formats line breaks), also add:

1add_filter( 'widget_text', 'shortcode_unautop' );

The same principle works for PHP templates. If you need to execute a shortcode directly in header.php or another theme file, wrap it in do_shortcode():

1echo do_shortcode( '[techblog]' );

This way the same logic is available in the editor, widget, and template, without duplicating code.

Escaping: how to show shortcode text without execution

Sometimes you need not to execute a shortcode but to show its syntax to the reader, as in this article. If you simply insert [gallery] in the editor, WordPress will immediately execute it or show a placeholder. There are two ways to avoid this.

Double square brackets. The simplest method, double the outer brackets:

1[[gallery]]

For paired tags, the first opening and last closing are doubled:

1[[maps]New York, USA[/maps]]

HTML character codes. In the text editor, you can replace brackets with their ASCII codes: &#91; instead of [ and &#93; instead of ]. The entry &#91;gallery&#93; will display as text [gallery], but won't be executed.

The first method is simpler and more readable in source code, the second is more reliable with complex formatting. Choose double brackets for quick edits in the text editor and ASCII codes when the shortcode neighbors other square brackets, for example inside code blocks or meta-field descriptions. In both cases, site visitors see exactly the shortcode text, and WordPress doesn't execute it.

Video: complete breakdown of WordPress shortcodes

For those who prefer visual explanation, here's a detailed tutorial from the Kinsta team. The author shows creation, debugging, and real examples of shortcodes in a live project, from theme installation to frontend output.

⁉️🤔 Frequently asked questions

Can you use shortcodes in Gutenberg?

Yes, via the "Shortcode" block in the block insertion panel. You insert the shortcode into the block field, and WordPress executes it during rendering. However, complex shortcodes with nested content may work unpredictably, in such cases it's more reliable to switch to code editing mode. Gutenberg renders shortcodes via server callback, so results depend on whether the function returns correct HTML. Block themes (Full Site Editing) with theme.json may partially restrict shortcode output in templates, check specific theme compatibility.

What to do if a shortcode doesn't work?

Check three typical causes. First: you inserted the shortcode in visual editor, which converted brackets to HTML entities, switch to text mode and make sure the brackets are straight. Second: the plugin registering the shortcode is deactivated, go to "Plugins" and check status. Third: the shortcode function uses echo instead of return, this is a developer error, output appears in the wrong place on the page. Systematic diagnostic method: open wp-config.php, enable WP_DEBUG and WP_DEBUG_LOG. After loading the page with the shortcode, check wp-content/debug.log, there will be specific PHP errors indicating file and line.

Can you insert PHP code directly into a shortcode?

No. A shortcode is a trigger, not a container for arbitrary code. The function registered on the server side via add_shortcode() executes. If you need custom logic, write it in functions.php (or in a separate plugin) and bind it to the shortcode. Between square brackets you can only pass content and attributes, not executable code. For safe PHP execution in content, explore plugins like "Code Snippets", they let you manage snippets through the admin interface without editing functions.php and with protection against fatal errors.

Do shortcodes slow down the site?

By themselves, no. add_shortcode() merely registers correspondence of tag and function in the global $shortcode_tags array. Overhead arises when the shortcode function performs heavy database queries or external API calls on every page load. The problem isn't in the shortcode mechanism, but in the specific plugin implementation. Guideline: if a page contains 20+ shortcodes, each pulling WP_Query or wp_remote_get(), cache results via Transients API. For typical scenarios (one or two shortcodes per page), performance impact is negligibly small.

How to remove a shortcode from output without deleting it from the post?

Use remove_shortcode() in functions.php. For example, to disable the built-in gallery: remove_shortcode( 'gallery' ). After this, [gallery] in the post text will display as ordinary text in square brackets, without execution. Comes in handy when migrating to another solution or debugging conflicts. Partial disabling: you can override a shortcode by registering your own handler with the same tag via add_shortcode(). The last registered handler has priority.

Is it worth learning shortcodes in 2026

Gutenberg and the block editor closed many tasks for which shortcodes were previously written: columns, buttons, media insertion, wrappers. But shortcodes haven't gone anywhere. Plugins still register them by the hundreds, from subscription forms to WooCommerce carts. And most importantly, one custom shortcode can replace a plugin and do exactly what your project needs, without overloading the admin with someone else's settings.

If you regularly repeat the same HTML block, link, or template in articles, spend 10 minutes on add_shortcode() in functions.php. Return on investment: dozens of hours per year that you don't spend on copy-paste. Shortcodes are backwards compatible, code written today will work in future WordPress versions, because the shortcode API hasn't changed since its appearance and remains one of the most stable core elements.