WordPress Logo – Athemeart WordPress Themes

WordPress Shortcode Fundamentals: A Complete Beginner-to-Expert Guide

Sooner or later every WordPress site needs a contact form, a product grid, a pricing table or a promo banner dropped into the middle of a page. Nobody wants to paste fifty lines of HTML and PHP every time. A WordPress shortcode fixes that with one short line of text: you type it, WordPress swaps it for the real thing.

This guide takes you from “what is a shortcode in WordPress?” all the way to writing, securing, debugging and cleaning up your own shortcodes. You will get working code you can copy, a clear comparison with Gutenberg blocks, a troubleshooting checklist, and a section most tutorials skip: what to do with the leftover [shortcode] text after you remove a plugin.

Quick answer: a WordPress shortcode is a tag in square brackets, such as [gallery], that WordPress replaces with the output of a PHP function when the page loads. You can use it in posts, pages, widgets and theme files, and you can create your own with add_shortcode().

What you will learn

  • What shortcodes are, how WordPress processes them and which types exist
  • How to use shortcodes in posts, blocks, widgets, menus and theme files
  • How to create custom shortcodes with attributes, enclosed content and a custom plugin
  • How to fix shortcodes that show as plain text or render nothing
  • How shortcodes compare with Gutenberg blocks, and when each one wins
  • How to secure, speed up and cleanly remove shortcodes

1. What Are WordPress Shortcodes?

A WordPress shortcode is a short piece of text wrapped in square brackets that tells WordPress to run a specific PHP function and drop the result into your content. When a visitor opens the page, WordPress finds the tag, calls the function attached to it and replaces the tag with whatever that function returns.

Here is the smallest useful example:

[gallery ids="12,15,18" columns="3"]

That single line becomes a three-column image gallery. You did not write any HTML, CSS or PHP in the post. The heavy lifting lives in one function, registered once, and reused anywhere.

Why shortcodes exist

The Shortcode API arrived in WordPress 2.5. Before it, the only way to add dynamic output inside a post was to run PHP in the content, which is messy, hard to maintain and a security risk. Shortcodes gave plugin and theme developers a safe, standard way to say “put this feature here”, and gave site owners a copy-and-paste way to use it. The idea is close to the BBCode tags used on old forums, except a WordPress shortcode runs real server-side code.

Anatomy of a WordPress shortcodeAn enclosing shortcode split into opening bracket, tag name, attribute, closing bracket, content and closing tag.[buttonstyle=”outline”]Get started[/button]Tag nameAttribute = valueContent (enclosing only)Opening bracketClosing bracketClosing tag
Figure 1: the parts of an enclosing WordPress shortcode.

Where shortcodes show up in real sites

  • Plugins: contact forms, sliders, tables, booking widgets and review blocks usually hand you a shortcode to paste.
  • WooCommerce: product grids, cart, checkout and account pages have classic shortcodes, covered in our WooCommerce shortcodes guide.
  • Themes: many themes ship shortcodes for buttons, columns, alerts and icons.
  • Your own code: small helpers such as the current year, a company phone number or a call-to-action box.

One benefit deserves special mention: central control. If the same shortcode sits on thirty pages and you change its function once, all thirty pages update. You never edit thirty posts by hand.

2. How WordPress Shortcodes Work

Shortcodes feel like magic until you see the pipeline. WordPress stores your post content in the database exactly as you typed it, brackets included. Only when the page is displayed does WordPress run that stored text through a chain of filters, and one of them handles shortcodes.

How WordPress processes a shortcodePost content passes through do_blocks, wpautop, do_shortcode, your callback function and becomes HTML output.Stored postcontentdo_blocks()priority 9wpautop()priority 10do_shortcode()priority 11Your callbackreturns a stringHTML shownto the visitorRuns on every page view, inside the_content
Figure 2: the shortcode pipeline inside the_content.
  1. Registration: a plugin, theme or snippet calls add_shortcode() to link a tag name to a PHP function.
  2. Display: when a page loads, WordPress sends the stored content through the the_content filter.
  3. Scanning: the do_shortcode() function searches the text for tags that match a registered shortcode name.
  4. Execution: each match calls its function with the attributes and any enclosed content.
  5. Replacement: whatever the function returns replaces the bracketed text.

A simplified view of the core filters shows why order matters:

add_filter( 'the_content', 'do_blocks', 9 );
add_filter( 'the_content', 'wptexturize' );
add_filter( 'the_content', 'wpautop' );
add_filter( 'the_content', 'shortcode_unautop' );
add_filter( 'the_content', 'do_shortcode', 11 );

Three consequences follow from this pipeline, and they explain most shortcode bugs:

  • Only registered tags run. If WordPress does not know a tag, it leaves the brackets as plain text. That is what you see after you deactivate a plugin.
  • Callbacks must return, never echo. The result is inserted into a string, so echoing prints the output too early and in the wrong place.
  • Callbacks run on every view. A heavy query inside a shortcode is a heavy query on every page load unless you cache it.

The official Shortcode API documentation on WordPress.org describes the same model: a handler function that accepts attributes and returns the output.

3. Types of WordPress Shortcodes

Shortcodes come in two structural forms, and both can carry attributes. Knowing which form you are looking at tells you how to write and troubleshoot it.

Self-Closing Shortcodes

A self-closing shortcode stands alone, like an <img> tag in HTML. It does its job without wrapping any text. Galleries, forms, sliders and “show the cart” tags use this form.

[gallery ids="21,22,23" size="medium"]
[contact_form id="7"]
[ata_year]

You may also see a closing slash, such as [ata_year /]. It is optional but harmless, and it makes the intent obvious.

Enclosing Shortcodes

An enclosing shortcode has an opening tag and a closing tag with content in between. The function receives that content and can wrap, format or transform it.

[ata_notice type="warning"]Back up your site before updating.[/ata_notice]
[caption align="aligncenter" width="300"]A photo caption[/caption]

The closing tag uses a forward slash, exactly like HTML. If you forget it, WordPress treats the opening tag as self-closing and your content is left outside the wrapper.

Shortcode Attributes

Attributes are named options that change how a shortcode behaves. They work on both forms and use a name="value" pattern:

[gallery columns="4" size="large" orderby="rand"]

WordPress understands four attribute styles:

Style Example Notes
Double quotes columns="3" The safest and most readable choice
Single quotes columns='3' Handy when the value contains double quotes
No quotes columns=3 Works for simple values without spaces
Positional (unnamed) [ata_hello World] Arrives in the callback as $atts[0]; avoid it in new code

Two details trip people up. First, WordPress lowercases attribute names before passing them to your function. Second, every value arrives as a string, so show_price="false" is the text “false”, which PHP treats as true. We handle that properly in the code section below.

4. WordPress Shortcode Syntax Explained

The syntax is small, but the rules are strict. These are the valid shapes WordPress recognises:

[name]
[name /]
[name attribute="value" /]
[name attr1='value1' attr2="value2"]
[name]Enclosed content.[/name]
[name attribute="value"]Enclosed content.[/name]

Naming rules

  • Use lowercase letters, numbers, hyphens and underscores. Avoid spaces, slashes, angle brackets, ampersands and square brackets in a name.
  • Add a unique prefix, such as ata_, so your tag never collides with a plugin that picked button or box first.
  • Only one function can own a tag. If two plugins register the same name, the one that loads last wins.

Quotes, brackets and escaping

Always use straight quotes. If you paste a shortcode from a Word document, an email or a chat app, the quotes often turn into curly quotes (“ ”), and WordPress then reads them as part of the value instead of as delimiters. That one change breaks more shortcodes than any other typo.

To display a shortcode as text without running it, double the brackets, as in [[gallery]]. WordPress strips one pair and prints [gallery]. Inside a tutorial like this one, HTML entities (&#91; and &#93;) work too, and they are the safer choice inside code blocks.

Right and wrong at a glance

Wrong Right Why
[gallery columns=“3”] [gallery columns="3"] Curly quotes are not delimiters
[ gallery ] [gallery] The tag name must follow the bracket immediately
[ata_notice]Text [ata_notice]Text[/ata_notice] Enclosing shortcodes need a closing tag
[Gallery] [gallery] Tag names are case-sensitive
[gallery id=5 id=6] [gallery ids="5,6"] Repeating an attribute keeps only one value

Nesting shortcodes

You can place one shortcode inside the content of another, but only if the outer callback calls do_shortcode( $content ). You also cannot nest the same tag inside itself, because the parser matches the first closing tag it finds.

5. How to Use Shortcodes in WordPress

Knowing how to use a shortcode in WordPress comes down to one question: where do you want the output? Each location has its own method.

Adding Shortcodes to Posts and Pages

In the Classic editor, click where you want the output and type or paste the shortcode into the Visual or Text tab. It works immediately. In the block editor, use the dedicated block described next.

Using Shortcodes in Gutenberg Blocks

  1. Open the post or page and click the + inserter where you want the shortcode.
  2. Search for Shortcode and select the block.
  3. Paste the shortcode into the text field, for example [ata_year].
  4. Click Preview or Update. The editor shows the raw text, and the rendered result appears on the front end.

You can also type the shortcode straight into a Paragraph block. WordPress will still process it on the front end, but the Shortcode block keeps the markup tidy and makes the intent clear to other editors. If you build with a page builder, look for its shortcode widget; many of the best Elementor addons and Elementor itself include one.

Adding Shortcodes to Widgets

  1. Go to Appearance → Widgets.
  2. Open the widget area, such as a sidebar or footer, and click +.
  3. Add a Shortcode block (or a Text widget on older setups) and paste your shortcode.
  4. Click Update.

This is a clean way to add forms, newsletter boxes or promo banners to a sidebar without touching a template. Our guide to WordPress sidebars explains how widget areas are registered if you need a new one. On a very old theme that does not parse shortcodes in widgets, one line enables it:

add_filter( 'widget_text', 'do_shortcode' );

Using Shortcodes in WordPress Menus

Menus do not run shortcodes by default, so a shortcode typed into a menu item label shows up as raw text. If you really need dynamic text in a menu, such as a cart count or a year, run the finished menu HTML through do_shortcode():

add_filter( 'wp_nav_menu_items', 'do_shortcode' );

Use this only with shortcodes that return plain text or a small inline element, and only inside the label of a menu item. Shortcodes inside a link URL will not work, and complex block-level output inside a menu usually breaks the layout.

Adding Shortcodes to Theme Files

In a PHP template such as header.php, footer.php or single.php, call do_shortcode() and echo the result:

<?php echo do_shortcode( '[ata_year]' ); ?>

If the shortcode needs attributes, put them inside the string: do_shortcode( '[gallery ids="5,6,7"]' ). Edit a child theme rather than the parent so updates do not wipe your change.

On a block theme there is no PHP template to edit. Open Appearance → Editor, choose the template or template part, add a Shortcode block and paste the tag. The saved markup looks like this:

<!-- wp:shortcode -->
[ata_year]
<!-- /wp:shortcode -->
Location Works out of the box? How to use it
Posts and pages Yes Type it, or use the Shortcode block
Widgets Yes in modern WordPress Shortcode block or Text widget
Theme templates No echo do_shortcode( '...' );
Block theme templates Yes Shortcode block in the Site Editor
Menus No Filter wp_nav_menu_items
Manual excerpts, custom fields No Pass the value through do_shortcode()

6. How to Create Custom WordPress Shortcodes

Ready to create a WordPress shortcode of your own? The recipe never changes: write a PHP function that returns a string, then register it with add_shortcode(). Everything below uses the prefix ata_ to avoid name clashes, and every example escapes its output.

Creating a Basic Shortcode

Our first shortcode prints the current year, which is perfect for a footer that never goes out of date.

function ata_year_shortcode() {
	return esc_html( wp_date( 'Y' ) );
}
add_shortcode( 'ata_year', 'ata_year_shortcode' );

Use it as [ata_year] in any post, widget or template. Notice the function uses return. Swapping it for echo is the single most common beginner bug.

Creating Shortcodes with Attributes

Attributes make one shortcode flexible. WordPress hands your function an array called $atts, and shortcode_atts() merges it with defaults so missing options never cause notices. This button shortcode also validates its values:

function ata_button_shortcode( $atts, $content = '', $tag = '' ) {
	$atts = shortcode_atts(
		array(
			'url'     => '#',
			'style'   => 'primary',
			'new_tab' => 'false',
		),
		$atts,
		$tag
	);

	$allowed_styles = array( 'primary', 'secondary', 'outline' );
	$style          = in_array( $atts['style'], $allowed_styles, true ) ? $atts['style'] : 'primary';
	$new_tab        = wp_validate_boolean( $atts['new_tab'] );
	$label          = '' !== trim( $content ) ? $content : __( 'Read more', 'athemeart' );

	return sprintf(
		'<a class="ata-button ata-button--%1$s" href="%2$s"%3$s>%4$s</a>',
		esc_attr( $style ),
		esc_url( $atts['url'] ),
		$new_tab ? ' target="_blank" rel="noopener noreferrer"' : '',
		esc_html( $label )
	);
}
add_shortcode( 'ata_button', 'ata_button_shortcode' );

Now you can write:

[ata_button url="https://example.com/pricing" style="outline" new_tab="true"]See pricing[/ata_button]

Three habits in that code are worth copying everywhere. The style is checked against an allow-list, the URL goes through esc_url(), and the string “false” is converted with wp_validate_boolean() instead of being trusted as a PHP boolean.

A data-driven example

Shortcodes are great for numbers that change by themselves. This one prints how many published posts of a given type exist, using wp_count_posts() (see our wp_count_posts guide for the full return object):

function ata_post_count_shortcode( $atts ) {
	$atts = shortcode_atts( array( 'type' => 'post' ), $atts, 'ata_post_count' );
	$type = sanitize_key( $atts['type'] );

	if ( ! post_type_exists( $type ) ) {
		return '';
	}

	$counts = wp_count_posts( $type );

	return esc_html( number_format_i18n( (int) $counts->publish ) );
}
add_shortcode( 'ata_post_count', 'ata_post_count_shortcode' );

Write “We have published [ata_post_count] articles” and the number stays correct as you publish more. Pass type="product" to count WooCommerce products.

Creating Enclosing Shortcodes

An enclosing shortcode receives the text between its tags in the second argument, $content. This notice box wraps that text in a styled container:

function ata_notice_shortcode( $atts, $content = null ) {
	if ( null === $content || '' === trim( $content ) ) {
		return '';
	}

	$atts  = shortcode_atts( array( 'type' => 'info' ), $atts, 'ata_notice' );
	$types = array( 'info', 'success', 'warning', 'error' );
	$type  = in_array( $atts['type'], $types, true ) ? $atts['type'] : 'info';

	return sprintf(
		'<div class="ata-notice ata-notice--%1$s" role="note">%2$s</div>',
		esc_attr( $type ),
		wp_kses_post( do_shortcode( $content ) )
	);
}
add_shortcode( 'ata_notice', 'ata_notice_shortcode' );

Calling do_shortcode( $content ) lets editors nest other shortcodes inside the notice, and wp_kses_post() strips anything that is not safe post HTML. Usage:

[ata_notice type="warning"]Back up your database before you update.[/ata_notice]

Adding Shortcodes Using a Custom Plugin

A plugin keeps your shortcodes alive when you change themes, which is the main reason to prefer it over functions.php. Create the folder wp-content/plugins/athemeart-shortcodes/, add a file named athemeart-shortcodes.php and paste this:

<?php
/**
 * Plugin Name: aThemeArt Shortcodes
 * Description: Small, reusable shortcodes for the site.
 * Version:     1.0.0
 * Author:      aThemeArt
 * License:     GPL-2.0-or-later
 * Text Domain: athemeart-shortcodes
 */

defined( 'ABSPATH' ) || exit;

final class ATA_Shortcodes {

	public static function init() {
		$shortcodes = array(
			'ata_year'       => 'year',
			'ata_cart_count' => 'cart_count',
		);

		foreach ( $shortcodes as $tag => $method ) {
			add_shortcode( $tag, array( __CLASS__, $method ) );
		}
	}

	public static function year() {
		return esc_html( wp_date( 'Y' ) );
	}

	public static function cart_count() {
		if ( ! function_exists( 'WC' ) || null === WC()->cart ) {
			return '';
		}

		return '<span class="ata-cart-count">' . esc_html( (string) WC()->cart->get_cart_contents_count() ) . '</span>';
	}
}
add_action( 'init', array( 'ATA_Shortcodes', 'init' ) );

Activate it under Plugins and both tags work everywhere. The second one is a WooCommerce example: it prints the number of items in the visitor’s cart, and it quietly returns nothing when WooCommerce is not active. Remember that full-page caching can freeze a cart count, so exclude cart-aware pages from the cache or load the number with the cart fragments technique described in our WooCommerce hooks list.

Registering on the init hook, as above, matches the recommendation in the WordPress documentation and avoids load-order surprises.

Adding Shortcodes Using the Functions.php File

You can paste the same functions into your theme’s functions.php. It is the fastest route, with one big catch: the moment you switch themes, those shortcodes disappear and every page that uses them shows raw bracket text.

  1. Create and activate a child theme (the guide linked in section 5 explains how) so a parent update cannot overwrite your code.
  2. Open Appearance → Theme File Editor and select the child theme’s functions.php, or edit the file over SFTP.
  3. Paste your functions at the bottom and wrap each one in a guard so a duplicate name cannot cause a fatal error:
if ( ! function_exists( 'ata_year_shortcode' ) ) {
	function ata_year_shortcode() {
		return esc_html( wp_date( 'Y' ) );
	}
}
add_shortcode( 'ata_year', 'ata_year_shortcode' );

If you would rather not touch theme files at all, a snippets plugin is a safe middle ground. Our roundup of code snippets for WordPress shows how to manage and switch snippets on and off without editing PHP files, and a broken snippet disables itself instead of taking the site down.

7. What Are WordPress Shortcodes? A Beginner’s Guide

If the code above felt like a lot, here is the same idea with no PHP at all. Think of a shortcode as a speed-dial button. Someone else (a plugin, a theme or a developer) stores the long phone number. You only press the short button, and WordPress dials.

Your first shortcode in four steps

  1. Pick a feature that offers a shortcode, such as a gallery or a plugin’s form.
  2. Copy the tag exactly, including the brackets and the straight quotes.
  3. Paste it into a Shortcode block, a widget or the Classic editor.
  4. Preview the page on the front end. The editor may show only the raw tag.

The six built-in shortcodes

WordPress ships with a handful of shortcodes that work on any theme, with no plugin needed:

Shortcode What it does Example
audio Embeds an audio file with the built-in player [audio src="/uploads/episode-1.mp3"]
video Embeds a video file with the built-in player [video src="/uploads/demo.mp4" width="640"]
gallery Builds an image gallery from the media library [gallery ids="4,5,6" columns="3"]
playlist Shows a playlist of audio or video files [playlist type="audio" ids="9,10"]
embed Embeds external content with set dimensions [embed width="600"]https://example.com/video[/embed]
caption Adds a caption to an image (also available as wp_caption) [caption width="300"]...[/caption]

Popular WooCommerce shortcodes

If you run a store, these classic tags save a lot of time. Newer WooCommerce installs build Cart and Checkout with blocks by default, but the shortcode versions still work and many themes and extensions rely on them. The full list, with every attribute, lives in the WooCommerce shortcodes article linked in section 1.

Shortcode Purpose
[products limit="4" columns="4"] Shows a product grid
[product_page id="99"] Shows a full single-product page
[add_to_cart id="99"] Shows an add-to-cart button for one product
[woocommerce_cart] Cart page content
[woocommerce_checkout] Checkout page content
[woocommerce_my_account] Customer account area

When a shortcode is the right tool

  • You need the same feature on many pages and want one place to change it
  • The place you are editing has no block inserter, such as a template file
  • A plugin you rely on only offers a shortcode
  • You are working with older content that already uses them

8. How to Fix Shortcodes Not Working in WordPress

When a shortcode misbehaves, it almost always falls into one of five groups. Work through them in order, and keep WP_DEBUG on a staging copy so PHP errors are visible. If a fix triggers a fatal error or a blank screen, our list of common WordPress errors shows how to recover quickly.

Shortcode Displays as Plain Text

If visitors see [my_tag] instead of the output, WordPress did not find a registered function for that tag. Check:

  • The plugin or theme is active. A deactivated plugin leaves its tags unregistered.
  • The name matches exactly. Tags are case-sensitive, and a missing underscore is enough to fail.
  • Registration happens early enough. Register on init, not on a late hook that fires after the content is rendered.
  • The area processes shortcodes. Templates, menus and custom fields need do_shortcode().

To confirm what WordPress knows about, temporarily list every registered tag in the admin and delete the snippet afterwards:

add_action( 'admin_notices', function () {
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}
	global $shortcode_tags;
	echo '<div class="notice notice-info"><p>' . esc_html( implode( ', ', array_keys( $shortcode_tags ) ) ) . '</p></div>';
} );

Shortcode Is Not Rendering

If the tag disappears but nothing appears, the function ran and returned an empty string, or it printed its output too early.

  • Use return, not echo. Echoed output lands at the top of the page, outside your content.
  • Look at your conditions. A callback that returns '' when an attribute is missing will look broken; test with all defaults.
  • Clear caches. Page, object and CDN caches can serve the old output.
  • Check the attributes. A wrong ID, such as a deleted form, often produces silent empty output.

Plugin or Theme Conflicts

Because only one function can own a tag, two plugins that both register [slider] will fight, and the later one wins. To test for a conflict, switch to a default theme, deactivate other plugins one by one and watch when the output returns. As a developer, protect yourself with a unique prefix and, where it matters, check first:

if ( ! shortcode_exists( 'ata_year' ) ) {
	add_shortcode( 'ata_year', 'ata_year_shortcode' );
}

Incorrect Shortcode Syntax

Use this checklist before blaming anything else:

  • Straight quotes only, no curly quotes from copy and paste
  • No space between the opening bracket and the tag name
  • A closing tag for every enclosing shortcode
  • No stray HTML tags or non-breaking spaces inside the brackets (switch to the Code editor to check)
  • Attribute values with spaces are wrapped in quotes

Shortcode Not Working in Widgets or Templates

In a PHP template, wrap the shortcode in do_shortcode() and echo it. In a legacy widget area, enable processing with the filter shown in section 5. For manual excerpts and custom fields, pass the value through the function yourself:

echo do_shortcode( get_post_meta( get_the_ID(), 'promo_text', true ) );

Automatic excerpts are different: WordPress deliberately strips shortcodes from them, so nothing is wrong when a tag does not appear in a generated excerpt.

9. WordPress Shortcodes vs Gutenberg Blocks: What’s the Difference?

Blocks are the future of editing in WordPress, but shortcodes are far from dead. The real skill is knowing which one fits the job. If you are choosing a theme with this in mind, our comparison of block themes vs classic themes shows how the two worlds affect your options.

Key Differences

Feature Shortcodes Gutenberg blocks
Editing experience Text tag, no live preview Visual, with a preview and a settings panel
Learning curve Easy to paste, PHP needed to build Easy to use, JavaScript and React to build
Where it works Content, widgets, templates, almost anywhere with a filter The editor, the Site Editor and block widgets
Reuse One function powers every instance Reusable blocks, patterns and synced patterns
Portability Tag text moves between sites Block markup moves with the post, needs the block installed
Output Always server-rendered PHP Static or dynamic (server-rendered)
Long-term direction Stable, maintained, rarely extended Where core and most plugins are investing

Advantages and Disadvantages

Shortcodes: pros

  • Work in templates, widgets and menus
  • Trivial to copy between sites
  • One function, many pages
  • Simple to write in plain PHP

Shortcodes: cons

  • No live preview in the editor
  • Raw text appears if the plugin goes away
  • Attributes are easy to mistype
  • Easy to write insecurely

Blocks: pros

  • See the result while you edit
  • Friendly settings panels for editors
  • Style controls and patterns built in
  • Better fit for block themes

Blocks: cons

  • Harder to build, needs a JavaScript toolchain
  • Not available in plain PHP templates
  • Missing block shows as a warning if the plugin is removed
  • Can bloat markup if overused
Shortcode or block decision guideA three-question guide: widget, menu or template needs a shortcode; live preview needs a block; reuse on many pages favours a shortcode or dynamic block.Is the output needed in a widget,menu or PHP template?Do editors need a live visualpreview while writing?Is one function reused onmany pages?Use a shortcodeUse a Gutenberg blockShortcode or dynamic blockYesYesYesNoNoStill no? A plain block or pattern is enough.
Figure 3: a quick way to choose between a shortcode and a block.

When to Use Shortcodes

  • You need output inside a PHP template, a menu label or a widget area
  • A plugin exposes a feature only as a shortcode
  • You maintain a large library of older content that already depends on them
  • You want one function to control a repeated element across the site

When to Use Gutenberg Blocks

  • Editors and clients should see what they are building as they type
  • You are building on a block theme and the Site Editor
  • The element needs rich design controls, such as spacing, colour and typography
  • You want users to insert it from the block inserter without remembering syntax

You do not have to pick a side forever. Developers can register a block that renders on the server with the same PHP function as an existing shortcode, and a block can include a transform that converts a pasted shortcode into the block automatically. Core is already moving in this direction: WooCommerce now offers block versions of its Cart and Checkout alongside the classic shortcodes. Neither format is inherently faster; speed depends on the code and the assets it loads.

10. How to Remove Unused Shortcodes from WordPress

Deactivate a form, slider or page-builder plugin and you often discover ugly leftovers: visitors now see [old_slider id="12"] in the middle of a page. This section shows how to find and clean them up properly.

Why Unused Shortcodes Appear

The shortcode text lives in your post content. The function that turned it into something useful lived in the plugin or theme. Remove the function and the text stays, and because WordPress ignores tags it does not recognise, the brackets are printed as they are. The same happens when you switch themes that defined shortcodes in functions.php.

How to Identify Unused Shortcodes

Before you delete anything, take a full backup. Then list every place the tag appears. With WP-CLI:

wp post list --post_type=any --post_status=any --s="old_slider" --fields=ID,post_title,post_type,post_status

Or run a direct database query (change the wp_ prefix if yours is different):

wp db query "SELECT ID, post_type, post_status, post_title FROM wp_posts WHERE post_content LIKE '%[old_slider%' AND post_type NOT IN ('revision','auto-draft')"

Without command-line access, use the search box on the Posts and Pages screens, and search page-builder templates, widgets and theme options too. Tags can hide in more places than posts.

Removing Shortcodes from Posts and Pages

  1. Decide per tag: replace it with a block, a new shortcode or nothing at all.
  2. Test on staging first with a dry run.
  3. Run the replacement: for an exact tag, a search-replace removes it from post content.
wp search-replace '[old_slider id="12"]' '' wp_posts --include-columns=post_content --dry-run

Remove --dry-run when the report looks right. For tags with many different attributes, or while you clean up gradually, hide the dead tags at display time. This small filter strips both the opening and closing tags of the names you list, and keeps any content that sat between them:

add_filter( 'the_content', 'ata_hide_dead_shortcodes', 12 );
function ata_hide_dead_shortcodes( $content ) {
	$dead_tags = array( 'old_slider', 'old_form' );

	foreach ( $dead_tags as $tag ) {
		$content = preg_replace( '/\[\/?' . preg_quote( $tag, '/' ) . '(?:\s[^\]]*)?\]/', '', $content );
	}

	return $content;
}

Priority 12 runs after do_shortcode(), so live shortcodes are processed first and only the dead ones are removed. WordPress also ships strip_shortcodes(), which removes every registered shortcode from a string, useful for building plain-text summaries.

Cleaning Up Shortcode Plugin Data

Once the content is clean, the plugin may have left options, post meta and custom tables behind. Check, then delete deliberately:

wp option list --search="*old_slider*" --fields=option_name
wp db query "SELECT DISTINCT meta_key FROM wp_postmeta WHERE meta_key LIKE '%old_slider%'"
wp db tables "*old_slider*" --all-tables

Only delete rows and tables you have identified and backed up. If the plugin offers a “delete data on uninstall” option, switch it on before you delete the plugin.

11. WordPress Shortcode Best Practices

Good shortcodes are boring: predictable, safe and quick. These five areas separate the ones that last from the ones that become tomorrow’s support ticket.

Security and Data Sanitization

Treat every attribute and every piece of enclosed content as untrusted input. Contributors and authors can type shortcodes into posts, so a careless callback lets them inject scripts into pages other people view. This is not theoretical. In March 2026 a stored cross-site scripting flaw (CVE-2026-2480) was disclosed in the Shortcodes Ultimate plugin, affecting versions up to 7.4.10; the cause was insufficient sanitization and escaping of attributes in one of its shortcodes, and the Wordfence advisory tracks it. The lesson applies to any plugin: sanitize on the way in, escape on the way out.

Value Sanitize or validate Escape on output
Plain text sanitize_text_field() esc_html()
URL esc_url_raw() esc_url()
Number or ID absint() esc_html()
CSS class or key sanitize_html_class() or sanitize_key() esc_attr()
Limited HTML wp_kses_post() Already filtered
Boolean flag wp_validate_boolean() Not needed

Our dedicated guide to sanitizing, escaping and validating data goes deeper on each function. A few more rules:

  • Never pass an attribute to eval(), include, unserialize() or a raw SQL query. Use $wpdb->prepare() for any query.
  • If a shortcode outputs a form, add a nonce and check capabilities on submit.
  • Use allow-lists for options such as styles and types, as the button example did.

Performance Optimization

Shortcodes run on every page view, so keep them light.

  • Load assets only when needed. Do not enqueue a stylesheet on every page just because one page uses the shortcode:
add_action( 'wp_enqueue_scripts', function () {
	global $post;

	if ( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, 'ata_notice' ) ) {
		wp_enqueue_style( 'ata-notice', plugins_url( 'css/notice.css', __FILE__ ), array(), '1.0.0' );
	}
} );
  • Cache expensive results. Store slow lookups, such as remote API calls, in a transient:
function ata_remote_stat_shortcode() {
	$html = get_transient( 'ata_remote_stat' );

	if ( false === $html ) {
		$html = '<strong>' . esc_html( ata_expensive_lookup() ) . '</strong>';
		set_transient( 'ata_remote_stat', $html, HOUR_IN_SECONDS );
	}

	return $html;
}
add_shortcode( 'ata_remote_stat', 'ata_remote_stat_shortcode' );
  • Avoid queries inside loops. A shortcode used on an archive page runs once per post.
  • Keep markup lean. Fewer wrapper elements means less to render and less to style.

Accessibility Considerations

Shortcode output becomes part of your page, so it must meet the same accessibility bar as everything else. The W3C’s is a good checklist to measure your output against; WCAG 2.2 became a W3C Recommendation in October 2023.

  • Return semantic HTML: real buttons and links, lists for lists, one heading level at a time
  • Never rely on colour alone to show a warning or an error
  • Give interactive elements visible focus and a keyboard path
  • Add accessible names for icons and image-only links
  • Let editors supply alt text for any image a shortcode outputs

SEO Considerations

  • Server-side output is crawlable. Search engines see the rendered HTML, not the bracket tag, so content generated by a PHP shortcode counts as page content.
  • Raw tags look sloppy. A leftover [tag] can appear in snippets and on the page. Clean it up as shown in section 10.
  • Keep headings in order. A shortcode that injects an <h1> into a post breaks the document outline.
  • Do not repeat thin blocks. The same shortcode output on hundreds of pages adds duplication without adding value.
  • Watch speed. Slow shortcodes hurt Core Web Vitals, which is why caching and conditional assets matter.

Maintainable Shortcode Development

  • Prefix everything: tags, functions, classes and CSS classes.
  • Keep one shortcode per function, and keep markup separate from logic where you can.
  • Put shortcodes in a plugin or a must-use plugin, not in a theme, so a redesign does not break content.
  • Add a short docblock listing each attribute, its default and its allowed values.
  • Keep a living reference of your tags and where they are used. It makes audits and removals painless.
  • Store code in version control and test changes on staging before production.

12. Advanced WordPress Shortcode Development

Once the basics feel natural, the Shortcode API gives you precise control over registration, parsing and output.

Using WordPress Shortcode API

Here is the full toolkit at a glance:

Function or filter What it does
add_shortcode( $tag, $callback ) Registers a shortcode
remove_shortcode( $tag ) Unregisters one shortcode
remove_all_shortcodes() Unregisters every shortcode
shortcode_exists( $tag ) Checks that a tag is registered
has_shortcode( $content, $tag ) Checks that a string contains a registered tag
do_shortcode( $content ) Processes shortcodes inside a string
shortcode_atts( $pairs, $atts, $tag ) Merges attributes with defaults
shortcode_parse_atts( $text ) Parses an attribute string into an array
strip_shortcodes( $content ) Removes registered shortcodes from a string
get_shortcode_regex() Returns the regular expression WordPress uses
pre_do_shortcode_tag / do_shortcode_tag Filters to short-circuit or modify a tag’s output

Every callback receives up to three arguments: the attributes array, the enclosed content, and the tag name. The tag argument lets you share one callback across several registered names.

Handling Shortcode Attributes with shortcode_atts()

Passing the shortcode name as the third parameter turns on a filter named shortcode_atts_{$shortcode}. It lets a child theme or another plugin change your defaults without editing your code:

add_filter( 'shortcode_atts_ata_button', function ( $out, $pairs, $atts ) {
	$out['style'] = 'outline';
	return $out;
}, 10, 3 );

To parse an attribute string yourself, for example one stored in a custom field, use shortcode_parse_atts():

$parsed = shortcode_parse_atts( 'id="5" size=large featured' );
// array( 'id' => '5', 'size' => 'large', 0 => 'featured' )

Processing Shortcodes with do_shortcode()

Use do_shortcode() anywhere WordPress does not do it for you: template files, custom fields, REST responses you assemble yourself, or nested content inside an enclosing shortcode.

$content = get_post_meta( get_the_ID(), 'intro_text', true );
echo wp_kses_post( do_shortcode( $content ) );

When a shortcode builds a large chunk of HTML, output buffering keeps the callback readable. Pull the markup from a template file instead of concatenating strings:

function ata_pricing_shortcode( $atts ) {
	$atts = shortcode_atts( array( 'plan' => 'basic' ), $atts, 'ata_pricing' );

	ob_start();
	include plugin_dir_path( __FILE__ ) . 'templates/pricing.php';
	return ob_get_clean();
}
add_shortcode( 'ata_pricing', 'ata_pricing_shortcode' );

Inside pricing.php, read $atts and escape every value as usual.

Checking Shortcode Existence with shortcode_exists()

Two functions sound alike but answer different questions. shortcode_exists() asks whether a tag is registered. has_shortcode() asks whether a string contains a registered tag:

if ( shortcode_exists( 'ata_button' ) ) {
	// The function is registered and available.
}

if ( has_shortcode( get_post_field( 'post_content' ), 'ata_button' ) ) {
	// This post actually uses the shortcode.
}

Use the first before registering or overriding. Use the second to load assets only on pages that need them.

Removing Shortcodes with remove_shortcode()

You can disable a plugin’s shortcode or replace it with your own version. Run the code after the original registration, which means a later hook or a higher priority number:

add_action( 'init', function () {
	remove_shortcode( 'vendor_slider' );
	add_shortcode( 'vendor_slider', 'ata_custom_slider' );
}, 20 );

Registering and Unregistering Shortcodes

Registration is not limited to the front end. You can register a shortcode conditionally, for example only for logged-in users or only when a plugin is active, and unregister it for contexts where it should not run:

add_action( 'init', function () {
	if ( is_admin() ) {
		return;
	}

	if ( class_exists( 'WooCommerce' ) ) {
		add_shortcode( 'ata_cart_count', array( 'ATA_Shortcodes', 'cart_count' ) );
	}
} );

Keeping admin screens free of front-end shortcode logic avoids wasted queries on the dashboard. Finally, remember that a shortcode and a block can share the same renderer. Write the PHP once, expose it through both, and give editors the interface they prefer.

13. Common WordPress Shortcode Mistakes to Avoid

  1. Echoing instead of returning. Output appears at the top of the page. Always return a string.
  2. Skipping the prefix. Generic names such as [button] or [box] collide with plugins.
  3. Trusting attributes. Unsanitized values are the root of most shortcode vulnerabilities.
  4. Using curly quotes. Pasting from documents or chat apps silently breaks attributes.
  5. Forgetting the closing tag. An enclosing shortcode without [/tag] loses its content.
  6. Treating “false” as false. Attribute values are strings. Convert them with wp_validate_boolean().
  7. Hiding shortcodes in the theme. Moving to a new theme turns your content into raw bracket text.
  8. Running heavy queries on every view. Cache results and limit loops.
  9. Loading assets on every page. Enqueue scripts and styles only where the shortcode appears.
  10. Leaving dead tags behind. Clean up content before you delete a plugin, not after.
  11. Nesting the same tag. The parser cannot match a shortcode inside itself.
  12. Editing production directly. One typo in functions.php can take the whole site down; use staging and a snippets plugin.

14. Frequently Asked Questions (FAQs)

Are WordPress Shortcodes Still Relevant?

Short answer: yes.

Blocks have taken over many jobs inside the editor, but shortcodes remain the standard way to add dynamic output to templates, widgets and menus. Thousands of plugins still ship them, WooCommerce keeps classic shortcodes for cart, checkout and product displays, and most older sites depend on them. Expect them to keep working for a long time.

Can I Use Multiple Shortcodes on One Page?

Short answer: yes, as many as you need.

Each tag is processed independently, and you can repeat the same shortcode with different attributes. The only caveats are performance (each one runs its function) and nesting: you can place a different shortcode inside an enclosing one if the outer callback calls do_shortcode(), but you cannot nest a tag inside itself.

Can I Use Shortcodes Inside PHP Files?

Short answer: yes, with do_shortcode().

In any theme or plugin file, write echo do_shortcode( '[your_tag]' );. Be sure the shortcode is registered before that line runs, which is normally the case in a template because init has already fired. In a block theme, use a Shortcode block in the template instead.

Do Shortcodes Affect Website Performance?

Short answer: only if the code behind them is slow.

A shortcode is just a function call, so a lean one costs almost nothing. Problems come from heavy database queries, remote requests on every view, and scripts or styles loaded site-wide. Cache expensive results with transients, enqueue assets conditionally with has_shortcode(), and measure with a profiling tool before you optimise.

What Happens When I Deactivate a Shortcode Plugin?

Short answer: the raw tag text appears on your pages.

The tag stays in your post content, but WordPress no longer knows what it means, so visitors see the bracket text. Nothing is deleted from the database, which means reactivating the plugin restores the output. If you are removing the plugin for good, follow the cleanup steps in section 10 to strip the leftover tags and plugin data.

Are WordPress Shortcodes SEO-Friendly?

Short answer: yes, when they output clean server-side HTML.

Search engines see the final rendered page, so content produced by a PHP shortcode is treated like any other content. What hurts SEO is slow output, broken heading order, thin repeated blocks and visible leftover tags. Build shortcodes that return semantic, lightweight markup and they will not get in the way.

15. Conclusion: Mastering WordPress Shortcodes

Shortcodes turn one line of text into a feature. You now know what a shortcode is, how WordPress finds and runs it, how to use shortcodes in posts, widgets and templates, and how to write your own with attributes and enclosed content. You also have a debugging checklist, a clean removal routine and the security habits that keep your output safe.

A good next step is small. Register one shortcode, such as [ata_year], in a tiny plugin. Add an attribute, escape the output, then test it on staging. Once that feels easy, move on to caching, conditional assets and templates. Mastery comes from repeating that cycle on real problems.

Remember the four rules that prevent most trouble: return instead of echo, always use a unique prefix, sanitize input and escape output, and put shortcodes in a plugin rather than a theme. Follow them and your shortcodes will stay fast, safe and easy to maintain for years.

Inspire us with your love!

Saiful Islam

By Saiful Islam

Saiful Islam, the founder of aThemeArt, is a successful freelancer, a father of two boys, and an enthusiast in coding, YouTube, and gaming. Connect with me on Twitter, Facebook, and Instagram to stay updated with my latest endeavors.

You can check also

Leave a Reply

Your email address will not be published. Required fields are marked *.

*
*