Plugins Plugin hub Backup SEO Caching Security Forms WooCommerce Images Best backup plugins
Hosting Hosting directory Shared hosting Managed WordPress Cloud hosting VPS hosting By reader location Hosting finder
Themes & builders Compare Rank Math vs Yoast
Tools All tools Hosting finder Plugin stack builder Cost calculator Salt generator Theme detector Who is hosting this? Speed test Headline analyzer robots.txt generator Redirect generator Uptime calculator Blog name generator
Blog Best backup plugins Deals
Guides All guides Speed up WordPress Choose hosting Back up WordPress
How we test

Developer · Guide

How to Write Shortcode in WordPress (Step by Step)

How to Write Shortcode in WordPress (Step by Step)

Short answer

Write a PHP function that returns your HTML, then register it with add_shortcode() in a custom plugin, child theme or code snippets plugin. Add attributes with shortcode_atts() and escape every value. Then place the tag in square brackets in a Shortcode block, and it renders when the page loads.

Key takeaways

  • A shortcode is a PHP function linked to a tag with add_shortcode().
  • Always return output; echoing puts it in the wrong place.
  • Use shortcode_atts() to set defaults for attributes.
  • Escape output with esc_html(), esc_attr() and esc_url().
  • Store shortcodes in a plugin so they survive theme changes.
  • Prefix tag names to avoid clashes with other plugins.

How do you write a shortcode in WordPress?

Write a PHP function that returns your output, register it with add_shortcode() in a small plugin or a child theme, then type the tag in square brackets in any post or page.

A shortcode is a small tag, such as [my_button], that WordPress swaps for real content when the page loads. The code behind it lives in PHP, not in the post.

Writing your own takes only a few lines. The main skills are knowing where to put the code, how to accept attributes, and how to return clean, safe output.

If you want the background first, read our explainer on what a shortcode is in WordPress. This guide focuses on writing one from scratch.

What do you need before writing a shortcode?

You need a place to store PHP code that survives theme updates, such as a small custom plugin, a child theme or a code snippets plugin, plus a staging site for testing.

Avoid editing the functions.php file of a theme you downloaded. A theme update replaces that file and your shortcode disappears.

Here are the usual options:

Where to put the codeGood forWatch out for
Small custom pluginShortcodes you want to keep if you change themesYou maintain the file yourself
Child theme functions.phpShortcodes tied to one designLost if you switch themes
Code snippets pluginQuick additions without file accessSnippets depend on that plugin staying active
Parent theme functions.phpNothingOverwritten on theme updates

A custom plugin is usually the best home. Our guide on how to create a WordPress plugin shows how to make the file and header.

If you prefer a child theme, see what a child theme is first. Snippet plugins such as Code Snippets let you paste PHP from the dashboard.

Always test on a staging copy. A single PHP typo can take the site down until you fix the file.

Step 1: How do you write a basic shortcode?

Create a callback function that builds and returns a string, then register it with add_shortcode() using a unique tag name.

Here is the smallest working example:

<?php
function wpl_year_shortcode() {
    return date_i18n( 'Y' );
}
add_shortcode( 'wpl_year', 'wpl_year_shortcode' );

Now typing [wpl_year] in a post shows the current year. This is handy for copyright lines that would otherwise go out of date.

The add_shortcode() reference shows the two arguments: the tag and the callback.

Pick names carefully. Use lowercase letters, numbers and underscores, and add a short prefix so your tag does not clash with a plugin that uses the same word.

The official handbook advises being wary of hyphens in shortcode names, so underscores are the safer choice.

Step 2: Why must a shortcode return output instead of echoing it?

WordPress places the returned string where the tag sits, so echoing prints the output in the wrong place, usually above the post content.

This is the most common mistake in first shortcodes. The code seems to work, but the content jumps to the top of the page.

If your output is long HTML, use output buffering to capture it and then return it:

function wpl_notice_shortcode() {
    ob_start();
    ?>
    <div class="wpl-notice">
        <p>Free shipping on orders this week.</p>
    </div>
    <?php
    return ob_get_clean();
}
add_shortcode( 'wpl_notice', 'wpl_notice_shortcode' );

The PHP manual page for ob_start() explains how output buffering collects anything printed until you fetch it.

Buffering keeps the HTML readable while still following the return rule.

Step 3: How do you add attributes to a shortcode?

Accept an $atts array in your callback, merge it with defaults using shortcode_atts(), and use the cleaned values in your output.

Attributes let one shortcode do many jobs. For example, [wpl_button url=“/contact/” text=“Get in touch”] can build different buttons.

function wpl_button_shortcode( $atts ) {
    $atts = shortcode_atts(
        array(
            'url'  => '#',
            'text' => 'Learn more',
        ),
        $atts,
        'wpl_button'
    );

    return sprintf(
        '<a class="wpl-button" href="%s">%s</a>',
        esc_url( $atts['url'] ),
        esc_html( $atts['text'] )
    );
}
add_shortcode( 'wpl_button', 'wpl_button_shortcode' );

The shortcode_atts() reference explains how it fills in missing attributes and drops ones you did not define.

Passing the tag name as the third argument lets other code filter your defaults. It is optional but good practice.

Attribute names are converted to lowercase before they reach your function. Write your defaults in lowercase so they match.

Step 4: How do you write an enclosing shortcode?

An enclosing shortcode wraps text between an opening and closing tag, and your callback receives that text as the second argument, $content.

Use this when the user should write the inner text, such as [wpl_box]Your text here[/wpl_box].

function wpl_box_shortcode( $atts, $content = null ) {
    $atts = shortcode_atts(
        array( 'color' => 'blue' ),
        $atts,
        'wpl_box'
    );

    return sprintf(
        '<div class="wpl-box wpl-box-%s">%s</div>',
        esc_attr( $atts['color'] ),
        do_shortcode( wp_kses_post( $content ) )
    );
}
add_shortcode( 'wpl_box', 'wpl_box_shortcode' );

The call to do_shortcode() lets other shortcodes inside the box run too. Without it, nested tags appear as plain text.

Running wp_kses_post() on the content keeps normal post HTML while removing anything unsafe. Our guide on how to sanitize and escape data in WordPress explains these functions.

Step 5: How do you use your shortcode on the site?

In the block editor, add a Shortcode block and type the tag, or type it straight into a paragraph, and it will render on the front end.

The Shortcode block is the cleanest way because it keeps the tag separate from your text. The Shortcode block documentation covers where it appears in the inserter.

Shortcodes do not render inside the editor. You see the raw tag while editing and the real output only when you preview or view the page.

You can also use shortcodes in these places:

  • Widget areas: add a Shortcode block to a sidebar or footer widget area.
  • Block theme templates: add a Shortcode block in Appearance, then Editor.
  • Theme files: call echo do_shortcode( '[wpl_year]' ); inside a template.

In theme files, calling your function directly is usually faster than parsing a tag. Use do_shortcode() when you need a plugin's shortcode and do not know its function name.

How do you keep a custom shortcode safe and fast?

Escape every value you output, avoid heavy database queries on each page load, and only load scripts or styles when the shortcode is actually used.

Anyone who can edit posts can type your shortcode and set its attributes. Treat those attributes like user input.

Follow these habits:

  1. Escape output with esc_html(), esc_attr() and esc_url() to suit the context.
  2. Check user permissions inside the callback if the shortcode shows private data.
  3. Cache expensive results with the Transients API instead of querying on every view.
  4. Enqueue CSS or JavaScript only when the shortcode appears on the page.

The Shortcode API handbook is the official reference for how parsing works, including nesting limits.

If your shortcode pulls posts from the database, read our guide on how to use WP_Query to build the query correctly.

Why is my shortcode not working?

A shortcode usually fails because the code is not loaded, the tag name is misspelled, the output is echoed, or a plugin or theme registered the same tag.

Check these causes one at a time:

  1. The tag shows as plain text. The registering code is not running. Confirm the plugin is active or the snippet is enabled.
  2. The output appears at the top of the page. Your function echoes instead of returning.
  3. A different output appears. Another plugin uses the same tag. Add a unique prefix.
  4. Nested shortcodes show as text. Call do_shortcode() on $content in the enclosing callback.
  5. A blank or broken page. A PHP error stopped the site. Check the error log.

You can test whether a tag is registered with shortcode_exists( 'wpl_button' ), which returns true or false.

For PHP errors, our guide on how to check PHP error logs shows where to find the message.

Should you write a shortcode or a custom block?

Write a shortcode for small, quick output that also needs to work in classic content or theme files, and build a custom block when editors need a visual preview and controls.

Shortcodes are simple and portable. They work in the block editor, the Classic Editor and many page builders.

Blocks give a better editing experience because users see the result while they write. They take more work to build, since they usually need JavaScript.

Many plugins offer both. If you plan a block later, our guide on how to create a custom block in WordPress shows the starting point.

What happens to content if you remove a shortcode?

If the code that registers a shortcode is removed, WordPress no longer replaces the tag, so the raw text in square brackets appears on every page that used it.

This is why it pays to store shortcodes in a plugin rather than a theme. Switching themes would otherwise leave stray tags across your site.

If you must retire a shortcode, you can register the same tag with a function that returns an empty string. That hides old tags until you clean up the content.

To find where a shortcode is used, search your posts for the tag in the dashboard or with a search and replace tool on a staging site.

Frequently asked questions

Where do I put shortcode code in WordPress?

The safest place is a small custom plugin, because it keeps working if you change themes. A child theme functions.php file or a code snippets plugin also works. Avoid editing a downloaded parent theme, since updates replace its files and remove your code.

Can I write a shortcode without PHP?

Not really. Shortcodes are registered in PHP. Some plugins let you build shortcode-like content from the dashboard, such as reusable content or snippet tools, but they still run PHP behind the scenes. For simple reusable text, synced patterns in the block editor can be an alternative.

Why does my shortcode output show at the top of the post?

Your callback is echoing or printing output instead of returning it. WordPress places the returned value where the tag sits. Build a string and return it, or wrap printed HTML in output buffering with ob_start() and return ob_get_clean().

Can shortcodes be used inside other shortcodes?

Yes, with enclosing shortcodes. The outer callback must run do_shortcode() on its $content so the inner tags are processed. The same tag cannot be nested inside itself reliably, so use different tags for inner and outer levels.

Do shortcodes slow down WordPress?

A simple shortcode adds very little load. Problems come from shortcodes that run heavy database queries or call external services on every page view. Cache those results with transients and load scripts only when the shortcode is used on the page.

Sources

  1. The Shortcode API WordPress Developer Resources
  2. add_shortcode() WordPress Developer Resources
  3. shortcode_atts() WordPress Developer Resources
  4. Shortcode Block WordPress.org Documentation
  5. ob_start PHP Manual

Is your product missing, or something out of date?

Tell us what to add or correct. We read every note and reply when we need a source. A message does not buy a ranking.

About the editors

Written and checked byWPLegible Editorial Team Independent WordPress reviews and guides

Researched from the primary sources listed above and checked against our editorial rules before publishing.