WPGEARED2.0.
WordPress Development

WordPress shortcode examples: create shortcodes with attributes

Published
Share Report:

To create a WordPress shortcode, register its name with add_shortcode() and return the HTML from its callback. Put the code in a small site plugin, then insert the shortcode into a Shortcode block. Attributes let each instance display different content without changing the PHP.

The examples below share one plugin: a year, a link with attributes, an enclosed notice and a recent-posts list. Each example shows what the callback receives and how to make its output safe.

1. Create a plugin for the examples

Use a local or staging site first. Keep a recoverable backup and file-manager or SFTP access so you can disable the plugin if you mistype PHP. Do not edit WordPress core or paste these functions into several places.

Create the folder wp-content/plugins/wpgeared-shortcodes, then create wpgeared-shortcodes.php inside it. Paste this complete file. The PHP opening tag appears once, at the top. There is no closing tag.

The wpgeared_ prefix reduces the chance of colliding with another plugin's tags or functions. Shortcode names share a global registry, so a second registration using the same name can replace the first. WordPress documents this registration behavior.

<?php
/**
 * Plugin Name: WPGeared Shortcode Examples
 * Description: Four small shortcode examples for a local or staging site.
 * Version: 1.0.0
 */
defined( 'ABSPATH' ) || exit;

function wpgeared_register_shortcodes() {
    add_shortcode( 'wpgeared_year', 'wpgeared_year_shortcode' );
    add_shortcode( 'wpgeared_link', 'wpgeared_link_shortcode' );
    add_shortcode( 'wpgeared_notice', 'wpgeared_notice_shortcode' );
    add_shortcode( 'wpgeared_recent_posts', 'wpgeared_recent_posts_shortcode' );
}
add_action( 'init', 'wpgeared_register_shortcodes' );

function wpgeared_year_shortcode() {
    return esc_html( wp_date( 'Y' ) );
}

function wpgeared_link_shortcode( $atts ) {
    $atts = shortcode_atts(
        array( 'text' => 'Read more', 'url' => home_url( '/' ) ),
        $atts,
        'wpgeared_link'
    );
    return '<a class="wpgeared-link" href="' . esc_url( $atts['url'] ) . '">'
        . esc_html( $atts['text'] ) . '</a>';
}

function wpgeared_notice_shortcode( $atts, $content = null ) {
    return '<div class="wpgeared-notice">'
        . wp_kses_post( (string) $content ) . '</div>';
}

function wpgeared_recent_posts_shortcode( $atts ) {
    $atts = shortcode_atts( array( 'count' => 3 ), $atts, 'wpgeared_recent_posts' );
    $count = max( 1, min( 10, (int) $atts['count'] ) );
    $query = new WP_Query(
        array(
            'post_type'           => 'post',
            'post_status'         => 'publish',
            'posts_per_page'      => $count,
            'ignore_sticky_posts' => true,
            'no_found_rows'       => true,
            'orderby'            => 'date',
            'order'              => 'DESC',
        )
    );
    if ( ! $query->posts ) {
        return '<p>No published posts yet.</p>';
    }
    $html = '<ul class="wpgeared-recent-posts">';
    foreach ( $query->posts as $post ) {
        $title = get_the_title( $post );
        $html .= '<li><a href="' . esc_url( get_permalink( $post ) ) . '">'
            . esc_html( '' !== $title ? $title : 'Untitled post' ) . '</a></li>';
    }
    return $html . '</ul>';
}

Activate WPGeared Shortcode Examples under Plugins. The remaining examples are content to insert into WordPress, not more PHP to add to the plugin.

2. Start with the year shortcode

Add a Shortcode block to a test page and enter:

[wpgeared_year]

The callback returns the year from wp_date(), which uses the site's configured timezone. It does not print directly while WordPress is still assembling the page.

return hands the value to the shortcode parser, which places it where the tag appears. echo inside the callback can send output at the wrong point. The shortcode handbook describes the return-value contract.

This is still server-generated content. If a full-page cache stores the rendered page, it can keep the previous year's output until that cached page is refreshed. A date function does not bypass caching.

3. Pass attributes to the link shortcode

Use quoted attributes to change one instance:

[wpgeared_link text="Read the guide" url="https://example.com/guide/"]

Without attributes, [wpgeared_link] uses “Read more” and the site's homepage. shortcode_atts() combines the supported defaults with the supplied values. An unsupported attribute is discarded. It is not a validator or sanitizer, so it does not replace the escaping in the returned markup. See the function reference.

The URL goes through esc_url(). The label goes through esc_html(). These are different contexts and need different escaping. A label containing HTML-like text should appear as text, not become a new element. A disallowed URL scheme should not survive as an executable link. Escaping does not tell you whether an allowed external destination is trustworthy, so choose destinations deliberately. WordPress's escaping guide explains the output contexts.

Keep attribute names lowercase. Quote values containing spaces and use straight quotes when entering the tag. For example:

[wpgeared_link text="News & updates" url="https://example.com/news/"]

The fixed wpgeared-link class is a styling hook. This example does not accept arbitrary CSS or class names from the shortcode.

4. Wrap content in an enclosed shortcode

An enclosed shortcode has an opening tag, content and a closing tag:

[wpgeared_notice]Please read the <strong>updated instructions</strong>.[/wpgeared_notice]

The content arrives separately from the attributes. This callback passes it through wp_kses_post(), which keeps permitted post HTML and removes disallowed markup. That allows a strong tag or ordinary link without treating all supplied HTML as safe.

This example intentionally does not call do_shortcode() on the enclosed content. Other shortcodes inside the notice will not automatically expand through this callback. Adding recursive processing changes the behavior and makes nested input harder to reason about. In particular, do not expect arbitrary nesting of the same shortcode name to work. The enclosing-shortcode documentation covers the parser's limitations.

The wrapper adds no visual design by itself. Your theme can style .wpgeared-notice, or you can add a small stylesheet to the plugin with the normal enqueue APIs. Do not add a global selector that unintentionally changes every div on the site.

5. List recent published posts

Insert:

[wpgeared_recent_posts count="3"]

The callback queries normal posts with a published status. It does not include drafts, private posts or custom post types. It converts count to an integer, then bounds the request between one and ten posts. Here, zero, a negative number or a nonnumeric value becomes one. A value above ten becomes ten.

That bound is deliberate. A shortcode on a public page should not permit an unbounded query just because an editor entered a large number. The example also skips pagination counts through no_found_rows, because it has no next-page control. The WP_Query reference describes these query arguments.

Each title and permalink is escaped when added to the list. The loop reads post objects directly instead of calling the_post(), so it does not replace the global post used by the surrounding template. If you rewrite it as a conventional secondary loop using the_post(), restore the original post afterward with wp_reset_postdata().

An empty site receives “No published posts yet.” An untitled post gets a readable fallback instead of an empty link. Both keep the list readable while you are still adding content.

6. Put the shortcode in the right place

Use a Shortcode block in the block editor, or enter the tag in Classic editor content. If your theme has a block-based widget area, its Shortcode block is another option. Do not assume a Custom HTML block or every third-party widget runs the shortcode parser.

A PHP template can parse a known shortcode explicitly:

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

Here the template prints the returned result. That does not change the rule that the shortcode callback itself returns its output. Pass a known string, not arbitrary visitor query parameters, to this API. Read the do_shortcode reference.

7. Check the normal and awkward cases

On staging, save the test page and view it while logged out. Check more than the default values:

  • The year appears where you placed its tag.
  • Two link instances can use different labels and destinations.
  • A label containing an ampersand or angle brackets stays readable.
  • The notice keeps allowed formatting without accepting a script element.
  • The recent-posts list respects the one-to-ten bound.
  • A draft and a private post do not appear in that list.
  • A test site with no published posts gets the empty-state message.

Then edit, save and reload the page in the editor. A PHP assertion can check a callback's output, but it cannot tell you whether a particular widget or editor integration behaves as expected.

Fix common shortcode problems

The tag appears as text. Confirm the plugin is active and the name is spelled exactly. Test in a Shortcode block before investigating a custom widget.

The output appears above the content. Look for echo, debug output or whitespace emitted by the callback. Return the finished string instead.

An attribute seems ignored. Check its lowercase name against the defaults. The link example supports text and url, not label or href.

The site shows a PHP error after editing. Restore the previous plugin file. If the dashboard is unavailable, rename this sample plugin's folder through your file manager to disable it, then fix the syntax before reactivating.

The output is old. Clear the relevant page cache after confirming that the uncached result is correct. Do not change working PHP to solve a cache problem.

Undo the examples, or choose a block

Before retiring the plugin, find and remove or replace its shortcode usages. Deactivation unregisters the tags but does not remove them from saved posts, so visitors can otherwise see literal shortcode text.

Shortcodes fit compact dynamic output and existing plugin integrations. A block is usually easier for editors who need visible controls, previews and structured content. The native Gutenberg block guide builds that alternative without a block-builder dependency. It is a different editing interface, not a promise that every block is faster than every shortcode.