Skip to main content
Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors

How to Create a Shortcode in WordPress: Custom PHP and WPCode

Illustration explaining WordPress shortcodes

A custom WordPress shortcode is a small bracketed tag, like [my_greeting], that WordPress replaces with dynamic content generated by a PHP function whenever it appears in a post, page, or widget. Creating one requires three parts: the shortcode tag, a callback function that generates the output, and the add_shortcode() call that registers the two together. Most guides tell you to paste this code directly into your theme’s functions.php file, genuinely risky for beginners, one syntax error there can take your entire site down. If a PHP change does cause a failure, see our guide to fixing WordPress critical errors safely. This guide uses WPCode instead, WebGomu’s established safe method for adding code, so a mistake stays contained rather than breaking your live site.

What Is a WordPress Shortcode?

A shortcode has three connected parts:

  • The tag: the bracketed text you place in content, such as [my_greeting].
  • The callback: a PHP function that produces the shortcode’s output.
  • The registration: an add_shortcode() call that connects the tag to the callback. This is part of the wider WordPress hooks system.

When WordPress processes a registered shortcode, it uses the callback’s returned string as the shortcode output.

A Real Example: Showing Category Descriptions in an Archive Template

On WebGomu, I created a [category_description] shortcode with WPCode and placed it in a Shortcode element in a reusable archive template built with Breakdance. It displays the description assigned to the current WordPress category. The reusable template was built with Breakdance; see our guide to using Breakdance Builder for the broader builder workflow. I can manage that description in the WordPress dashboard, and the archive template can display the updated text without manually adding the description to each category page.

This made the archive template reusable and kept category descriptions manageable from WordPress. I no longer have the exact original PHP snippet, so the code below is a reconstructed implementation of the behavior—not a claim that it is the code I originally used:

function category_description_shortcode() {
    $category = get_queried_object();

    if ( ! $category || ! isset( $category->term_id ) || ! isset( $category->taxonomy ) || 'category' !== $category->taxonomy ) {
        return '';
    }

    return term_description( $category->term_id, 'category' );
}
add_shortcode( 'category_description', 'category_description_shortcode' );

The example checks the current queried object and confirms it is a category before returning its description. Add and test code in the context where you intend to use it; the current queried object may differ on other types of pages.

Where to Add Your Shortcode PHP

I’ve added custom shortcode functions using both WPCode and a theme’s functions.php. I generally prefer WPCode or a similar snippet-management plugin when I want to manage functionality independently of the theme. Adding code to functions.php is also an option, but theme changes or updates can affect where custom code belongs. Choose the method that fits how the site is maintained, and make sure you know how to disable or remove the code if needed.

How to Create a Basic Shortcode With WPCode

  1. In the WordPress dashboard, install and activate WPCode if it is not already installed.
  2. Open the snippet area, choose to add a custom snippet, and select PHP as the code type. WPCode labels and menu locations can vary by version.
    WPCode Add Snippet
  3. Add a callback function and register its tag with add_shortcode().
    WPCode Create Custom Snippet
  4. Save and activate the snippet, then insert its tag in the editor or builder where it should appear.
  5. Open the actual front-end page and verify the output and surrounding layout.

Here is a simple instructional example:

function greeting_shortcode() {
    return '<p>Welcome to our site!</p>';
}
add_shortcode( 'greeting', 'greeting_shortcode' );

After activating the snippet, add [greeting] to a WordPress Shortcode block or a builder element that processes shortcodes.

Return Shortcode Output Instead of Echoing It

A shortcode callback should return its output string. WordPress uses that returned value as the shortcode’s output at the location where the shortcode is processed. For example:

function message_shortcode() {
    return '<p>This is the shortcode output.</p>';
}
add_shortcode( 'message', 'message_shortcode' );

This callback rule is different from printing output inside a PHP template. In a template, do_shortcode() processes a shortcode and returns the result; the template can then print it:

echo do_shortcode( '[category_description]' );

Use Shortcodes With Attributes

Attributes let a shortcode accept values when it is used. For example, a button shortcode might accept a URL and link text. This is a general instructional example, not a shortcode from my own site:

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

    return sprintf(
        '<a class="webgomu-button" href="%1$s">%2$s</a>',
        esc_url( $atts['url'] ),
        esc_html( $atts['text'] )
    );
}
add_shortcode( 'site_button', 'button_shortcode' );

Use it like this:

[site_button url="https://example.com" text="Visit our guide"]

shortcode_atts() applies the defaults when an attribute is omitted. Escape values for the context where they are output; this example uses esc_url() for the link and esc_html() for its text.

Enclosing Shortcodes: Process Content Between Tags

An enclosing shortcode has an opening tag, content, and a closing tag. I’ve built shortcodes with attributes and enclosed content. Here is an example of the markup I used for an accordion-style use case:

[accordion title="How do I process a refund?" default_open="false"]
To process a refund, navigate to WooCommerce > Orders, select the target order, and click the Refund button.
[/accordion]

The attributes and enclosed text are part of the shortcode markup. The PHP callback must be written to handle those attributes and the enclosed content; the markup alone does not define how the accordion is rendered.

How to Insert a Shortcode in WordPress or a Page Builder

In the WordPress block editor, insert a Shortcode block and enter the shortcode tag. If you are new to the editor, our Gutenberg Block Editor tutorial explains how blocks work. In my archive-template example, I placed [category_description] in a Shortcode element. The broader principle is to use the shortcode wherever WordPress or the tool you are working in processes shortcode tags, then verify the output in context.

How to Run a Shortcode in a PHP Template

If you need shortcode output at a specific location in a PHP theme template, call do_shortcode() with the shortcode string. For example:

echo do_shortcode( '[category_description]' );

I’ve used this approach when shortcode output needs to appear in a specific template location. In a visual template editor, I can usually place the shortcode directly in an element that processes shortcodes instead.

Test the Shortcode on the Front End

In my WordPress work, I’ve encountered shortcode errors that were not obvious PHP errors: the page could still load while part of the layout broke or the HTML structure was disrupted. That’s why I check the actual front-end page or template after adding or changing a shortcode. I verify that the expected content appears and that the surrounding layout and existing functionality still work.

Whether to use a backup or staging site depends on the task and the website. I don’t claim to use either before every small change. For higher-risk changes, consider the site’s backup and testing procedures before editing PHP. A WordPress staging site can give you a safer place to test the change before it reaches visitors. A snippet plugin changes how code is managed; it does not guarantee that a snippet cannot cause a problem.

Useful General-Purpose Shortcode Examples

The following are instructional examples, not claims about shortcodes I built for WebGomu. Add each as a PHP snippet, register its shortcode tag, and test it in the context where you plan to use it.

Display the Current Year

function current_year_shortcode() {
    return esc_html( wp_date( 'Y' ) );
}
add_shortcode( 'current_year', 'current_year_shortcode' );

Use: [current_year]

Show the Site Name

function site_name_shortcode() {
    return esc_html( get_bloginfo( 'name' ) );
}
add_shortcode( 'site_name', 'site_name_shortcode' );

Use: [site_name]

Show the Current Post’s Modified Date

function updated_date_shortcode() {
    if ( ! is_singular() ) {
        return '';
    }

    return esc_html( get_the_modified_date() );
}
add_shortcode( 'updated_date', 'updated_date_shortcode' );

Use: [updated_date]

Display a Post’s Featured Image

function featured_image_shortcode() {
    if ( ! has_post_thumbnail() ) {
        return '';
    }

    return get_the_post_thumbnail( get_the_ID(), 'large' );
}
add_shortcode( 'featured_image', 'featured_image_shortcode' );

Use: [featured_image]

Troubleshooting: If a shortcode appears as plain text, check that the snippet is active, the tag is spelled correctly, and the editor or builder element processes shortcodes. Then check the page’s front-end output.

Common Shortcode Mistakes to Check

  • Echoing from a shortcode callback instead of returning its output.
  • Using the shortcode tag before its PHP snippet is active or registered.
  • Inserting the shortcode into an element that does not process shortcodes.
  • Assuming a snippet-management plugin prevents all PHP or layout problems.
  • Skipping a front-end check after changing the shortcode or its template.

Key Takeaways

  • A shortcode connects a bracketed tag to a PHP callback through add_shortcode().
  • Return output from shortcode callbacks; use do_shortcode() when processing a shortcode in a PHP template.
  • WPCode and functions.php are both methods I’ve used; choose according to how the site’s code is managed.
  • My [category_description] example shows how a shortcode can display current category data in a reusable archive template.
  • Check the actual front end: a shortcode issue may affect layout or HTML even when the page still loads.

Frequently Asked Questions

Do I need coding experience to create a custom WordPress shortcode?

You need to add or adapt PHP code and understand where it will run. Start with a small callback, make sure you can manage or disable the snippet, and test the result on the front end.

Where should I add custom shortcode PHP?

I’ve used both WPCode and a theme’s functions.php. I generally prefer a snippet-management plugin when I want to manage the functionality independently of the theme. Theme changes or updates can affect where code in functions.php belongs.

Should a shortcode callback return or echo its output?

A shortcode callback should return its output string so WordPress can use it as the shortcode output. In a PHP template, do_shortcode() returns processed output, which the template can then print.

Can I use a shortcode in a page builder or template?

Yes, when the builder or template supports shortcode processing. I use shortcodes in different contexts; for my category-description example, I placed the shortcode in a Shortcode element in a reusable archive template.

Can I add a shortcode in the WordPress editor?

Yes. Use the WordPress Shortcode block and enter the registered shortcode tag. In a page builder, use an element that supports shortcode processing.

Can shortcodes accept attributes or wrap content?

Yes. Attributes pass values to a shortcode, and an enclosing shortcode can wrap content between opening and closing tags. For example, my accordion markup used a title, a default_open attribute, and enclosed refund instructions.

Can I run a shortcode inside a PHP template?

Yes. Call do_shortcode( '[your_shortcode]' ) in the template and print the returned result where it should appear. This is different from echoing output inside the shortcode callback.

Why should I check a shortcode on the front end?

I’ve seen shortcode errors disrupt layout or HTML without an obvious PHP error. Check the actual page or template where the shortcode runs, and verify both the expected output and surrounding layout.

Resources

Author:

Christoper Enolpe
Founder of WebGomu • WordPress Freelancer with 10+ Years of Experience

Christoper is the founder of WebGomu and a WordPress freelancer with over 10 years of hands-on experience building, optimizing, and maintaining WordPress websites. He writes practical, beginner-friendly guides based on real-world experience, covering WordPress, SEO, website performance, and AI tools to help readers build better websites with confidence.

Get one WordPress tip every week

Short, practical, no fluff — straight to your inbox.

Start Here

The Ultimate Beginner’s Guide to WordPress (2026): Build Your First Website Without Coding

Popular Guides

Our Partner

Breakdance builder with AI

More from the blog

Get one WordPress tip every week

Short, practical, no fluff — straight to your inbox.
No spam. Unsubscribe anytime.
Practical WordPress tutorials for beginners — step-by-step guides, SEO strategies, and performance tips.
© 2026 WebGomu. All rights reserved.
Built in Breakdance