Wordpress - How does a shortcode work?

When using the_content(), WordPress will run several filters to process the text coming from the editor. These filters process the content before it is sent to the browser. do_shortcode is the filter that handles shortcodes.

From /wp-includes/default-filters.php:

// Shortcodes
add_filter( 'the_content', 'do_shortcode', 11 ); // AFTER wpautop()

do_shortcode() is used to search content for shortcodes and filter the shortcodes through their hooks.

You can apply the do_shortcode filter to any string. For example, if you have a meta box with a text area and you would like to allow users to enter shortcodes in the text area, you could wire up the do_shortcode filter to handle that.

A shortcode example:

[my-shortcode param1=something param2=value]Text...[/my-shortcode]

When WordPress finds this shortcode in the content, it will run the function associated with the shortcode tag my-shortcode.

/**
 * An example shortcode.
 *
 * @param array $atts
 * @param string $content
 * @param string $tag Shortcode tag
 * @return string
 */
add_shortcode( 'my-shortcode', 'wpse_example_shortcode' );
function wpse_example_shortcode( $atts, $content = '', $tag ) {
    $a = shortcode_atts( [
            'param1' => false,
            'param2' => false,
    ], $atts );

    // code...

    return $content . '!!!';
}

In this case, WordPress will run the function wpse_example_shortcode() passing $atts (parameters and their values, e.g. param1, param2), $content (Text...), and $tag (the shortcode tag used, my-shortcode).

Valid shortcodes (including their parameters and content) will be replaced with the output of the callback function that they are associated with. Invalid shortcodes will be output just as they were entered in the back end.


Here's a little note:

The shortcode's API evolves around preg_replace_callback where we define the custom callbacks with our shortcode definitions.

The shortcodes in the text are parsed with a complex regular expression pattern that you can check out in the get_shortcode_regex().

The implementation of this in the core gets more complicated as we lay out the details ;-)

Tags:

Shortcode