Called in a shortcode?

When we register a shortcode, we assign a callback to the shortcode name:

add_shortcode( 'check', 'shortcode_check' );

function shortcode_check()
{
    return 1;
}

Dead simple. But our function can be called without the shortcode somewhere:

echo shortcode_check();

In some cases we might want to know how our function was called: in a shortcode or not.

There is no built-in function for that in WordPress, but we can use debug_backtrace(). It returns a list of all functions called before our callback, including all the arguments. Be aware this a very slow function, you should not use it if you don’t really have to.

To see if a function was called in a shortcode we can just use:

$in_shortcode = in_array( 
    'do_shortcode', 
    wp_list_pluck( 
        debug_backtrace(),
        'function' 
    ) 
);

Now we might want to know if our callback has been called in a specific shortcode, because we use the use the same callback for multiple shortcodes. Time for a separate, reusable function:

if ( ! function_exists( 'in_shortcode' ) )
{
    function in_shortcode( $name = '' )
    {
        $trace = debug_backtrace();

        foreach ( $trace as $entry )
        {
            if ( ! isset ( $entry[ 'function' ] ) )
                continue;

            if ( 'do_shortcode_tag' !== $entry[ 'function' ] )
                continue;

            if ( empty ( $name ) )
                return TRUE;

            if ( $name === $entry[ 'args' ][ 0 ][ 2 ] )
                return TRUE;
        }

        return FALSE;
    }
}

Now we can change our callback:

function shortcode_check()
{
    if ( ! in_shortcode() )
        return 'nope';

    if ( in_shortcode( 'check' ) )
        return 'checked';

    if ( in_shortcode( 'test' ) )
        return 'tested';

    return 'used in an unknown shortcode';
}

The return value will change depending on its context.

Author:

Web developer since 1998, moderator on WordPress Stack Exchange, author, manic reader.

Code is my drug.

Find Thomas Scholz on toscho.de⁠, ⁠, ⁠, ⁠, ⁠, ⁠, and .

1 Comment

  1. hakre – 16.10.2013 09:10

    Do we? If that is our function, we normally know when and how it is invoked, so introspection is normally not necessary.

    For debugging purposes, this can make sense however.

    Reply

Leave a Reply

Your email address will not be published.