Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
VGSources
Blog

How to Create and Use Shortcodes in WordPress

Build reliable WordPress shortcodes from scratch: register a unique tag, handle attributes and enclosed content, support nesting, escape output, choose plugin or theme placement, and fix raw shortcode text.
WorldWordPress Length10 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To create a custom WordPress shortcode, register a unique tag with add_shortcode(), point that tag to a PHP callback, and have the callback return the HTML or text that should replace the tag. You can then place the tag in post content as a self-closing shortcode such as [acme_notice type="warning" /] or wrap content with an enclosing form such as [acme_notice]Message[/acme_notice].

The reliable pattern is: put registration code in a plugin (so it survives a theme change), register it during WordPress initialization, define accepted attributes with shortcode_atts(), sanitize and escape every value for its output context, and use do_shortcode() when enclosed content can contain other shortcodes. If a shortcode appears as plain text, the tag is usually not registered, the callback is not loaded, or the content is not passing through a shortcode-aware filter.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What a WordPress shortcode does

A shortcode is a bracketed macro embedded in WordPress content. WordPress scans content for a registered tag, calls the PHP function associated with that tag, and replaces the bracketed expression with the string returned by the function. The replacement can be a paragraph, a notice box, a button, a list, or any other markup your callback safely generates.

Registration is the connection between the text a writer enters and the PHP that runs. Without registration, [acme_notice] has no meaning to WordPress and remains ordinary text. A tag should be lowercase and should use a distinctive prefix. A later registration of the same tag replaces the earlier callback, so generic names such as [box] or are collision-prone.

#1 Best Overall
Sale
Gaoye Blue Light Blocking Glasses
  • BLUE LIGHT BLOCKING GLASSES: Our blue light glasses for women boast UV400 protection, blocking harmful blue rays from computer screens. With these bluelight glasses women, you can enjoy gaming, reading, or watching TV with no worries of eye strain.
  • EYE RELIEF: Our blue light glasses are engineered to reduce blurry vision or strain caused by prolonged screen time. These womens blue light glasses aid in better sleep by preventing blue light from disrupting your natural sleep cycle, helping you fall asleep faster and enjoy a more restful night's sleep, making them the perfect christmas present.
  • COMFORTABLE: Crafted from durable material, our trendy blue light glasses for woman or blue light glasses men ensure long-lasting comfort. The high-transmittance lenses accessories, gamer gifts for men, help keep your eyes relaxed. Perfect stocking stuffers, gifts for gamers men, christmas gifts for men, halloween costumes.
  • LIGHTWEIGHT: These clear blue light glasses feature a lightweight frame, meaning they’ll stay comfy for long-term wear. Perfect as blue blockers glasses for women or mens blue light glasses, these non-prescription fake glasses for men can be worn throughout the day. The blue light blocking glasses women feature polycarbonate HD lenses, which are anti-reflective and restore true color.
  • WORRY-FREE PURCHASE: If you experience any issues, our support team is ready to assist you quickly. These are the perfect costume glasses for cosplay dressing up.

The processing sequence

  1. WordPress loads the plugin or theme code that contains your registration.
  2. add_shortcode() associates a tag, such as acme_notice, with a callback function.
  3. When content is filtered, WordPress identifies the bracketed tag and parses its attributes and enclosed content.
  4. The callback receives the parsed attributes and, for an enclosing shortcode, the inner content.
  5. The callback returns a replacement string, which WordPress inserts into the filtered content.

Where to put shortcode PHP

For a shortcode that should remain available when you change themes, place the code in a small custom plugin. Theme code is appropriate only when the shortcode is intentionally part of that theme’s presentation and you accept that it will disappear when the theme is removed or replaced.

Plugin placement

Create a PHP file in a plugin directory, add a normal WordPress plugin header, define the callback, and register the tag from the plugin’s initialization routine. The following complete example can be adapted for a plugin file:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<?php
/**
 * Plugin Name: Acme Notice Shortcode
 */

function acme_notice_shortcode( $atts, $content = null ) {
    $atts = shortcode_atts(
        array( 'type' => 'info' ),
        $atts,
        'acme_notice'
    );

    return '<div class="notice notice-' . esc_attr( $atts['type'] ) . '">' . esc_html( $content ?? '' ) . '</div>';
}

function acme_notice_register_shortcode() {
    add_shortcode( 'acme_notice', 'acme_notice_shortcode' );
}
add_action( 'init', 'acme_notice_register_shortcode' );

Save the file in its own plugin folder, activate that plugin in the WordPress admin, and then insert [acme_notice]Message[/acme_notice] into content. Registering on init ensures the tag is added during the normal WordPress loading sequence rather than only when a particular template happens to run.

Theme placement

If the shortcode belongs to a specific theme, the same function and add_shortcode() call can live in that theme’s PHP files. Keep the registration in code that loads on every request, not inside a template that runs only on one page. Before switching themes, replace theme-dependent shortcodes with a plugin implementation or expect existing posts to show the raw bracketed tags.

Build the smallest useful shortcode

The callback receives two important values. The first parameter contains attributes; the second contains enclosed content and is null for a self-closing use. A callback should return its replacement string and should not echo output. Echoing can place markup in the wrong location and can interfere with the content filter that is assembling the page.

Rank #2
Windex Gaming Cleaning Wipes, Pre-Moistened Wipes to Instantly Clean all Gaming Gear and Electronics, Resealable Packaging for a Freshness Lock, 25 count (Pack of 1)
  • WINDEX GAMING WIPES: effortlessly clean all your gaming gear and gaming electronics in one easy step with our new Windex Gaming Wipes
  • AMMONIA FREE: our ammonia-free formula is safe to use on all of your favorite gaming equipment like consoles, headsets, controllers, screens, keyboards, and more
  • PRE-MOISTENED WIPES: each wipe instantly removes dust, dirt, and stubborn smudges and fingerprints leaving a streak-free shine
  • ANTI-STATIC: great for cleaning and wiping down your gaming gear and electronics leaving behind no visible residue
  • COMPACT RESEALABLE PACKAGE: store your pack of Windex Gaming Wipes anywhere in your home for whenever a quick and easy wipedown is needed

Self-closing example

Use a self-closing form when the shortcode represents a fixed element and does not need inner text:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
[acme_notice type="warning" /]

The slash before the closing bracket is conventional but optional, so [acme_notice type="warning"] is also parsed as a self-closing shortcode.

Enclosing example

Use an opening and closing tag when the writer supplies text or other content:

[acme_notice]Your save is complete.[/acme_notice]

Do not try to combine both forms in one construct. A mixed expression that starts and closes like an enclosing shortcode while also adding a self-closing form is not interpreted as two independent shortcodes.

Define and use attributes safely

Attributes make one shortcode produce different output without duplicating PHP. WordPress passes the values in an array. shortcode_atts() lets you declare the keys your shortcode accepts, provides defaults for omitted keys, and ignores unknown keys.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
LISEN Cell Phone Stand Phone Holder for Desk, Office Decor Gadgets for Men
  • Ergonomic & Adjustable Design: Fight "text neck" and improve your posture. Designed for comfort, it offers an adjustable height (7.1in-8.5in) (1.4in adjustable range) and angle (5°-85°) Please note: cell phone stand is only 9 inches tall—the length of a standard pencil
  • Without blocking subtitles Perfect for office desk Tiktok Face Time Zoom video—this is the ultimate kitchen desk essential for phones! Perfect viewing experience while reducing neck back strain, A must-have for gamers streamers desk, and anyone who values both style and support!
  • Sleek & Stable Design fits Otterbox Case: Say goodbye to bent cables, tangles, and tip-overs! LISEN’s stylish adjustable desk phone holder features a built-in charging hole and smart cable management, keeping your phone secure and your workspace clutter-free cool gadgets for men
  • ANTI-SLIP DESIGN free hands: The under 10.00 items easy gadgets back and the bottom of this kitchen essentials for women are fully covered by anti-skid silicone, which LISEN stand up desk decor can provide maximum protection device from any scratches and slides
  • Your Perfect Viewing Companion:If your product arrives damaged or breaks within 365 days, reach out to LISEN for a quick and hassle-free solution. Struggling with assembly, like tightening the screw? We’ve got your back! Your experience matters to us. (Product including: phone Holder stand*1, screw*1, hexagon screwdriver*1, specification*1)
function acme_button_shortcode( $atts ) {
    $atts = shortcode_atts(
        array(
            'url'   => '#',
            'label' => 'Read more',
            'style' => 'primary',
        ),
        $atts,
        'acme_button'
    );

    return '<a class="button button-' . esc_attr( $atts['style'] ) . '" href="' . esc_url( $atts['url'] ) . '">' . esc_html( $atts['label'] ) . '</a>';
}
add_shortcode( 'acme_button', 'acme_button_shortcode' );

Authors can use that shortcode as [acme_button url="https://example.com" label="Open the guide" style="secondary" /]. Attribute names are lowercased while WordPress processes them, so define accepted keys in lowercase. Treat every value as untrusted input: validate allowed options, sanitize values where appropriate, and escape at the point where the value enters HTML.

Choose the correct escaping function

  • Use esc_html() for visible text, such as a message or button label.
  • Use esc_attr() for an HTML attribute or a class fragment.
  • Use esc_url() for a URL placed in an href or similar attribute.

Escaping is context-specific. A value that is safe as text is not automatically safe in an attribute, URL, class name, or query. Restrict values such as a notice type or visual style to the options your code actually supports instead of allowing arbitrary class names.

Handle enclosed content

For an enclosing shortcode, the callback’s $content parameter contains everything between the opening and closing tags. It can be empty, so code should tolerate null or an empty string. The minimal notice example uses esc_html( $content ?? '' ), which treats the enclosed value as text and prevents markup from being interpreted.

Allow nested shortcodes intentionally

If the enclosed area is supposed to contain other registered shortcodes, process it with do_shortcode( $content ) before wrapping it:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
function acme_panel_shortcode( $atts, $content = null ) {
    $atts = shortcode_atts(
        array( 'title' => '' ),
        $atts,
        'acme_panel'
    );

    $title = '';
    if ( '' !== $atts['title'] ) {
        $title = '<h3>' . esc_html( $atts['title'] ) . '</h3>';
    }

    return '<section class="panel">' . $title . do_shortcode( $content ?? '' ) . '</section>';
}
add_shortcode( 'acme_panel', 'acme_panel_shortcode' );

do_shortcode() scans the supplied content for registered tags and replaces them with their callbacks’ return values. If no tags are registered in that content, it simply returns the content without shortcode filtering. This is why nested markup may remain literal when the inner tag was never registered.

Rank #4
Ledagic IC+RGBW USB Powered Led Light Bar with App & Remote Control, 2 Pack
  • Easy Installation: Our gaming lights have been designed to enhance your entertainment experience. Simply position the led light bar next to your TV or game console to create a game room environment with ease. They come with USB power and a 60 inch cord for direct mounting and mobility
  • Audio Syncing & Extensive Mode: The built-in high-sensitivity music sensor allows you to sync the TV led lights to your favorite music. Lights react and move to the beat of music, film and game audio, creating an incredible immersive sound and light experience – and all without the need for an additional hub. You can choose from 64+ patterns, including strobe, illusion, jump, energy, gradient, running, chasing, fluttering mode etc. Each mode can be applied to different scenes
  • 64+ Chasing IC+RGB & W Effect: The independent control design of IC+RGB and white all-in-one multifunctional rgbw led bar lights monitor backlight allows you to easily switch the led lights for desk between IC+RGB and white to enjoy a variety of lighting effects, you can choose white lighting mode with high brightness for better illumination when working, etc. Choose IC+RGB lighting mode when you need to create an entertaining atmosphere for the light show, 16 million colours of Color changing rgb light bar let you dance to the beat and create a dynamic party atmosphere
  • Dynamic and Dimmable Lights: 1%-full brightness free brightness adjustment gives you the flexibility to adjust dimmable led light bar for room decorations or a variety of occasions
  • USB Powered: USB light bars for room can be powered by powernank, usb charger, TV, Monitor, laptop PC mainframe, making behind TV led lighting bar easy to install in any location.TV led lights are powered by the TV usb interface / PC mainframe, can be turned on/off synchronously with TV / PC

Only call do_shortcode() when nested shortcodes are part of the design. If the enclosed value is meant to be plain text, escape it instead; otherwise an author could insert markup or another shortcode where your interface expects a label.

Compare the implementation choices

Decision Use this when Syntax or consequence
Self-closing shortcode The component has no writer-supplied body. [acme_notice type="warning" /]; the callback receives no enclosed content.
Enclosing shortcode The author supplies a message or other inner content. [acme_notice]Message[/acme_notice]; the callback receives $content.
Fixed output The output is always the same apart from internal logic. Fewer accepted attributes and fewer validation paths.
Attribute-driven output Authors need controlled variations such as type, label, or URL. Declare defaults with shortcode_atts() and validate each option.
Flat content Inner text must remain text. Escape with esc_html(); do not run do_shortcode().
Nested shortcodes The component intentionally contains other shortcode components. Run do_shortcode( $content ) before wrapping the result.
Plugin registration The shortcode should survive a theme change. Register from plugin code, commonly during init.
Theme registration The shortcode is inseparable from one theme’s presentation. It is portable only with that theme and may become raw text after a switch.

Test a shortcode in a controlled order

  1. Activate the plugin or switch to the theme containing the code.
  2. Insert the exact registered tag, including spelling and lowercase characters, into a test post.
  3. Test the self-closing form first, then the enclosing form if your callback supports both.
  4. Omit each attribute once to confirm that its declared default is used.
  5. Pass an unknown attribute and verify that it does not alter output.
  6. Try an allowed and a disallowed value for options such as type or style; your validation should handle the latter predictably.
  7. If nesting is supported, put a second known shortcode inside the enclosing content and confirm that do_shortcode() processes it.
  8. Inspect the rendered HTML and check that text, attributes, classes, and URLs are escaped for their contexts.

Keep a test instance separate from production content while changing callback code. A PHP syntax error or a malformed return string can affect the entire request, while a controlled post makes it easier to identify whether registration, parsing, or rendering is at fault.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Fix a shortcode that appears as text

The tag is not registered

Confirm that the spelling in the post exactly matches the first argument passed to add_shortcode(). A typo, a changed prefix, or a plugin that is not active leaves the bracketed expression untouched.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The PHP file never loads

Ensure the plugin is activated and that registration code is outside a conditional or template path that does not run on the affected request. For theme code, verify that the active theme is the one containing the function.

The content is not shortcode-aware

WordPress replaces registered tags only when the content passes through a shortcode-aware filter. If a custom template, field, or application displays raw post data without applying the relevant content processing, the tag can remain visible even though registration is correct. Route that content through the same shortcode-aware processing your rendering context expects, rather than assuming every text field is parsed automatically.

Best Value
Sale
HUANUO FlowLift™ Dual Monitor Stand, Fully Adjustable Gaming Monitor Desk Mount for 13–32″ Computer Screens, Full Motion VESA 75x75/100x100 with C-Clamp & Grommet Base, Each Arm Holds 4.4 to 19.8 lbs
  • Compatible with Wide Screens - To ensure compatibility with the dual monitor mount, your each monitor must meet three conditions at the same time: First, computer screens size range: 13 to 32 inches. Second, screen weight range: 4.4 to 19.8 lbs. Third, the back of the monitor screen must have VESA mounting holes with a pitch of 75x75mm or 100x100mm.
  • Regarding the compatibility with desks - Your desk must meet three conditions at the same time: First, desk material: Only wooden desks are recommended, plastic or glass desks cannot be used. Second, desk thickness range: 0.59" - 3.54". Third, the bottom of the desk should not have any cross beams or panels, as this will interfere with installation. We recommend carefully checking that your desk and monitors meets all above conditions before purchasing.
  • Dual C-Clamp Hold - Worried your dual monitors might wobble or slip? Our upgraded base uses a larger platform plus a dual C-clamp structure to lock the dual monitor arm firmly to your desk. Each arm safely keeps your screens steady while you type, click and game—no shaking, no sliding, just a clean and secure setup you can trust every day. It also provides Grommet Mounting installation choice, both options ensure stable and secure fixation for your 0.59" - 3.54" desk.
  • Full-Motion Adjustment For Comfortable View - Pull the screen closer when you’re deep in a spreadsheet, push it back to watch videos, or rotate to portrait for coding — moving everything smoothly with just one hand. The monitor stand offers +85°/-50° tilt, ±90° swivel and 360° rotation. Raise your monitor up to 15.75″ to support a healthy sitting posture. Whether you’re working from home, gaming through the night, or switching between video calls and documents, getting the screens to your natural line of sight helps relieve neck, shoulder and back strain so you can stay focused longer with less fatigue.
  • Keep Your Desk Organized: By lifting both screens off the desktop, this dual monitor stand opens up valuable space for your keyboard, notebook, docking station or a simple, clutter-free work area. Built-in cable management guides wires along the arms, keeping cords out of sight and out of the way. Enjoy a tidy, modern workstation that looks as good as it feels to use.

The callback echoes instead of returning

Replace output statements with a returned string. The shortcode callback should produce no direct output of its own; WordPress inserts the returned value at the shortcode’s location.

The enclosing syntax is malformed

Use either a self-closing form or a properly paired opening and closing form. Check that the closing tag uses the same name and that you have not mixed both forms in one expression.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A nested shortcode remains literal

Check that the inner tag is registered and that the outer callback calls do_shortcode() on its enclosed content. Without that call, the outer callback will wrap the inner bracketed text rather than process it.

Display shortcode text literally

To show a registered shortcode as an example instead of executing it, double the brackets:

[[acme_notice]]

The doubled form tells WordPress to render the shortcode notation literally. Use it in documentation, tutorials, or editor-facing instructions where readers need to see the syntax itself.

Design conventions that prevent maintenance problems

  • Choose a distinctive, lowercase tag with a project prefix, such as acme_notice, to reduce collisions with plugins and themes.
  • Keep one responsibility per shortcode. A notice shortcode should not also perform unrelated database work or register several hidden tags.
  • Declare every supported attribute in one defaults array so the accepted interface is visible to future maintainers.
  • Validate enumerated values before using them in classes, URLs, queries, or other dynamic output.
  • Return a complete replacement string and keep rendering concerns inside the callback or a dedicated rendering function.
  • Escape at the final output context, even when a value came from a trusted-looking editor field.
  • Document whether the tag is self-closing, enclosing, or supports both, and show one valid example for each supported form.

A practical shortcode checklist

  1. Decide whether the component needs enclosed content, attributes, nesting, or only fixed output.
  2. Select a lowercase, prefixed tag that is unlikely to collide with another registration.
  3. Put persistent functionality in a plugin and load it during init.
  4. Write a callback with $atts and, when needed, $content = null.
  5. Use shortcode_atts() to define defaults and ignore unknown keys.
  6. Validate or sanitize every accepted value.
  7. Escape text, attributes, classes, and URLs with the function appropriate to each context.
  8. Return the replacement string; never echo from the callback.
  9. Call do_shortcode() only for enclosed content that is intentionally allowed to contain nested shortcodes.
  10. Test registration, both syntax forms, omitted attributes, invalid values, nesting, and literal display with doubled brackets.

Key takeaways

A shortcode is a registered tag-to-callback mapping, not merely text in square brackets. Registration makes the tag meaningful, the callback’s return value becomes the rendered replacement, and shortcode_atts() gives attributes a controlled interface with defaults. Enclosing tags provide $content; nested tags require do_shortcode(); and every dynamic value must be escaped for its output context. Use a prefixed plugin-based implementation when the shortcode must remain available across theme changes, and double the brackets whenever the syntax itself should appear on the page.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

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

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.