Skip to content
Snippet CSSGutenbergphp php

How to Create a Custom WordPress Shortcode

Learn to create a custom WordPress shortcode with PHP. Build a reusable notice box with attributes, safe output, and Gutenberg support.

Updated

Create Custom WordPress Shortcode
/**
 * Render a reusable notice box with [wdg_notice].
 *
 * Example: [wdg_notice text="Remember to save your changes." type="success"]
 *
 * @param array|string $atts Shortcode attributes.
 * @return string HTML for the notice box.
 */
function wdg_notice_shortcode( $atts = array() ) {
    $atts = shortcode_atts(
        array(
            'text' => 'This is a helpful notice.',
            'type' => 'info',
        ),
        (array) $atts,
        'wdg_notice'
    );

    $allowed_types = array( 'info', 'success', 'warning' );
    $type = is_string( $atts['type'] )
        ? sanitize_key( $atts['type'] )
        : 'info';

    if ( ! in_array( $type, $allowed_types, true ) ) {
        $type = 'info';
    }

    $text = is_string( $atts['text'] ) ? $atts['text'] : '';

    return sprintf(
        '<div class="wdg-notice wdg-notice--%1$s">%2$s</div>',
        esc_attr( $type ),
        esc_html( $text )
    );
}
add_shortcode( 'wdg_notice', 'wdg_notice_shortcode' );

Introdiction

A WordPress shortcode lets you insert reusable content into posts and pages with a small tag such as [wdg_notice]. Instead of repeatedly writing the same HTML, you define the output once in PHP and reuse it wherever you need it.

In this snippet, you’ll create a custom notice box shortcode with an optional message and three display styles: info, success, and warning.

What You’ll Build

A reusable [wdg_notice] shortcode that:

  • Displays a message inside a styled notice box.
  • Accepts text and type attributes.
  • Uses safe default values when attributes are omitted.
  • Escapes user-provided text and restricts styles to an allowed list.

The PHP Snippet

The complete PHP implementation is shown in the Primary Code panel for this Snippet. To use it on your own site, add that code to your child theme’s functions.php file or a small custom plugin.

You only need to install the PHP shortcode implementation once.

Where to Add the Code

Option 1: Child Theme

  1. Open wp-content/themes/your-child-theme/functions.php.
  2. Paste the PHP snippet into the existing file, outside any other function.
  3. Save the file. Do not add another <?php opening tag if the file already begins with one.

Use a child theme rather than editing the parent theme, so theme updates do not overwrite your work.

Option 2: Custom Plugin or PHP Snippet Plugin

Add the same PHP code to an active custom plugin or a PHP snippet managed by a code-snippet plugin. Follow the plugin’s instructions about whether the <?php opening tag is required. Do not install the same snippet in multiple locations.

How to Use the Shortcode in Gutenberg

  1. Edit a post or page in the WordPress block editor.
  2. Insert a Shortcode block (search for “Shortcode” or type /shortcode).
  3. Paste one of the examples below.
  4. Save the post and preview the frontend.

Default notice:

[wdg_notice]

Success notice:

[wdg_notice text="Your changes have been saved." type="success"]

Warning notice:

[wdg_notice text="Back up your site before editing files." type="warning"]

You can also use type="info" for a standard information message.

Optional CSS Styling

The PHP snippet creates the HTML, but CSS controls how the notice looks. Add this CSS to your child theme stylesheet (such as style.css) or your site’s custom CSS area:

.wdg-notice {
    margin-block: 1rem;
    padding: 1rem 1.25rem;
    border: 1px solid #bfdbfe;
    border-left: 4px solid #2563eb;
    border-radius: 8px;
    background: #eff6ff;
    color: #1e3a8a;
    line-height: 1.6;
}

.wdg-notice--success {
    border-color: #bbf7d0;
    border-left-color: #15803d;
    background: #f0fdf4;
    color: #166534;
}

.wdg-notice--warning {
    border-color: #fde68a;
    border-left-color: #b45309;
    background: #fffbeb;
    color: #92400e;
}

Without this CSS, the shortcode still produces a valid HTML div, but it will not have the custom notice-box appearance.

How It Works

1. add_shortcode() Registers the Tag

add_shortcode( 'wdg_notice', 'wdg_notice_shortcode' ) tells WordPress to call wdg_notice_shortcode() whenever it encounters [wdg_notice] in processed post content.

The wdg_ prefix helps avoid naming collisions with other themes and plugins.

2. shortcode_atts() Sets Defaults

shortcode_atts() combines the shortcode’s supplied attributes with the supported defaults. If a visitor sees [wdg_notice] without attributes, the function uses the default message and the info style.

3. The Style Is Validated

sanitize_key() normalizes the type, and in_array() only allows info, success, or warning. An unsupported type falls back to info rather than becoming an arbitrary CSS class.

4. Output Is Escaped and Returned

esc_attr() safely escapes the CSS-class value, while esc_html() makes the message plain text instead of executable HTML. The callback returns its HTML instead of printing it with echo, so WordPress places the output in the correct location.

Example Result

Using:

[wdg_notice text="Your changes have been saved." type="success"]

Produces a green notice box containing:

Your changes have been saved.

Important Notes

  • Text only: This simple shortcode intentionally displays plain text. HTML markup and nested shortcodes inside the text attribute are not rendered.
  • Quotes: Put attribute values in straight quotation marks ("like this") when they contain spaces.
  • Where it works: Use the Gutenberg Shortcode block or another context that processes WordPress shortcodes. A Code block will display the shortcode literally.
  • Avoid duplicates: Do not register the same shortcode in both your theme and a plugin. If the shortcode name is already registered elsewhere, the last registration can take precedence.
  • Theme changes: If the shortcode lives in a theme’s functions.php, it stops working when that theme is deactivated. A custom plugin keeps it available across theme changes.

Troubleshooting

**The page shows [wdg_notice] as text.** Confirm the PHP snippet is active and the tag is inside a Shortcode block rather than a Code block.

The notice appears but is not styled. Confirm the CSS was added to the active theme/site and that any caches were cleared.

A PHP error appears after saving. Recheck that the code was not pasted inside another function, that you did not duplicate the <?php opening tag, and that the callback name was not already defined.

Conclusion

A custom WordPress shortcode is an easy way to make a small UI element reusable. With add_shortcode(), shortcode_atts(), validation, and proper escaping, you can insert consistent notice boxes throughout your website without repeating HTML.

Official WordPress References