7

I know how to use shortcodes, even making them but what I need to understand is that a shortcode is a plain text stored in database as a post content, So how a plain text like this can be converted into dynamic.

What I want to know is how an x text can be handled before the server send it to the browser to behave deffirently?

12

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.

1
  • 2
    Thank you very much this answer is very helpful and made about 90% of information clear and I want another little thing to understand ..so I will post it in a new question but in general stackoverflow Jun 24 '17 at 10:49
4

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 ;-)

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.