arrow_back
Back

WordPress shortcodes: add_shortcode, attributes, and nested content

Andrew Dorokhov Andrew Dorokhov schedule 1 min read
menu_book Table of Contents

Shortcodes are the macros the editor can place inside the content, which WordPress replaces with generated markup when the post is rendered. Core ships with a few of its own:

[gallery]

[gallery size="large"]

Add a shortcode:

/**
 * Add a shortcode.
 */
add_shortcode('chair-picker-tool', [ self::class, 'shortcode' ]);

The simplest possible pair of a handler and its registration:

function time_shortcode( $atts ) {
    return date( "H:i" );
}

add_shortcode( 'time', 'time_shortcode' );

The callback must return the markup, not echo it.

Callback:

/**
 * Shortcode.
 *
 * @return string
 */
public static function shortcode() {

    return "<p>Test</p>";
}

Attributes

The $atts argument holds whatever the editor wrote inside the tag. Pass it through shortcode_atts() to merge it with the defaults, so that missing attributes don’t produce notices:

function time_shortcode( $atts ) {

    // Default values:
    $params = shortcode_atts( [
        'level' => 1,
        'label' => 'hello',
    ], $atts );

    return date( "H:i" ) . $params['level'] . $params['label'];
}

add_shortcode( 'time', 'time_shortcode' );

Rendering

Good practice to include files:

/**
 * Shortcode for the form.
 *
 * @return string
 */
public function shortcode_show_form()
{
    ob_start();

    require plugin_dir_path( __FILE__ ) . 'partials/shortcode-display.php';

    return ob_get_clean();
}
code

Need Help with Development?

Happy to help — reach out via the contacts or go straight to my Upwork profile.

work View Upwork Profile arrow_forward
Next Article

WordPress media library: attachments, uploads, and wp.media

arrow_forward