Age of Article Warning:
This article was originally published 21 months ago. The tips and techniques explained may be outdated, or information may longer be applicable. Please consider this when viewing the below content.

A WordPress shortcode is used to add extra functionality to your web page. It might be to add a print button onto a page, or perhaps a toggle accordion, Google Map, or even a Retweet button.

As well as outputting something to your web page, a shortcode can also be setup to allow passing parameters to a javascript file, which can be particularly useful if you need your shortcode to be used with a script file, and you want the flexibility to change certain variables depending on usage.

How can a shortcode pass data to a javascript file?

We use a WordPress function known as “wp_localize_script” that “localizes a registered script with data for a JavaScript variable”.

The steps are quite simple:

Step 1:
Register your scripts and styles ready to enqueue on pages that have the shortcode.

function some_scripts() {
     wp_register_style('my_stylecss', path to file);
     wp_register_script('my_script_handle', path to file, array(), '', true);
}
add_action('wp_enqueue_scripts','some_scripts');

Step 2:
Setup a shortcode function and add shortcode attributes to your array variable.

function my_shortcode($atts,$content=null) {
    $my_array_variable = shortcode_atts(array(
         'key1' => '',
         'key2' => ''
    ),$atts);

Step 3:
Then enqueue the scripts and styles in your shortcode, and include “wp_localize_script” on the line following the enqueued script, including the same handle as the enqueued script, a unique object name (eg: my_object_name), and the array variable from step 2.

wp_enqueue_style('my_stylecss');
wp_enqueue_script('my_script_handle');
wp_localize_script('my_script_handle','my_object_name',$my_array_variable);

Step 4:
Now besides accessing your attributes in the shortcode output (as per normal), you can also access the variables in your javascript file by using the unique object name and the attribute key (eg: my_object_name.key1)


/* example javascript file */
var some_variable_value = my_object_name.key1;
jQuery(document).ready(function($) {
     $("div").somefunction({some_variable: some_variable_value});
});

Important note: if passing integers you need to call the JavaScript parseInt() function.

In the next post I’ll demonstrate how to use wp_localize_script in a WordPress shortcode that adds a beautiful timer to your page, using jQuery TimeCircles

Passing Parameters from Shortcode to Javascript was last modified: September 6th, 2016 by David Tiong
Passing Parameters from Shortcode to Javascript