Get shortcode attributes outside shortcode function

You can pass an array to your script with wp_localize_script($handle, $object_name, $l10n).

function test_function( $atts )
{
    $data = shortcode_atts(
        array (
            'arrows' => TRUE
        ),
        $atts
    );
    wp_enqueue_script( 'your_script_name' );
    wp_localize_script(
        'your_script_name',
        'yourScriptObject',
        $data
    );

    return 'a string';
}

In your (external) script you can access the shortcode data now with …

var arrows = yourScriptObject.arrows;

… because WordPress will create a global accessible JavaScript with the name yourScriptObject now before it loads your external script.

Further shortcode attributes are available with yourScriptObject.othername or whatever the names are that you are using. For a more detailed example see my script in this answer.

Leave a Comment