Don’t Use do_shortcode()

The Internet abounds with examples of bad practices in WordPress development. Using do_shortcode() unnecessarily is one of the most pervasive.

do_shortcode() runs a fairly extensive regex (regular expression) that has to go through every possible shortcode. Konstantin Kovshenin has a good explanation of this:

That regex looks for all registered shortcodes within a string. For each match, it runs a replacement with a callback function, which also take the time to parse the shortcode attributes, before finally calling the actual callback function that’s been registered with add_shortcode.

Searching for the callback (function) and using it directly is preferable to using do_shortcode(). But what if you can’t? What if it’s in an object class?

Here is a simple utility function you can use to run a shortcode’s callback function, even if it’s in a class. It supports passing attributes and content.

/**
 * Call a shortcode function by its tag name.
 * 
 * Directly executes a shortcode's callback function using the shortcode's
 * tag name. Can execute a function even if it's in an object class.
 * Simply pass the shortcode's tag and an array of any attributes.
 *
 * @global array  $shortcode_tags
 * @param  string $tag            The shortcode tag name.
 * @param  array  $atts           The attributes (optional).
 * @param  array  $content        The shortcode content (null by default).
 *
 * @return string|bool False on failure, the result of the shortcode on success.
 */
function do_shortcode_func( $tag, array $atts = array(), $content = null ) {
 
    global $shortcode_tags;
 
    if ( ! isset( $shortcode_tags[ $tag ] ) ) {
        return false;
    }
 
    return call_user_func( $shortcode_tags[ $tag ], $atts, $content, $tag );
}

Leave a comment

Your email address will not be published. Required fields are marked *