1

I am developing a plugin, and I would like to make data available to the client-side JS code executed by one of my shortcodes. wp_localize_script seems like the obvious way to do that, but it's not working for me: my script is included, but not the JS data. The data depends on a value in the querystring, read by the shortcode. I suspect something to do with the relative timing of scripts and shortcodes in the WP lifecycle. I have some JS code not used in a shortcode that is happily being provided with data using wp_localize_script.

Abbreviated plugin file:

function shortcode_orderitem() {

    $id = intval($_GET['id']);
    $productData = retrieveSingleProductData($id);
    wp_localize_script('orderitem', 'productData', $productData); //THIS DOES NOT WORK
    return orderItem_buildHTML($productData);
}

function enqueue_general_scripts()
{
    wp_enqueue_script('orderitem', plugin_dir_url(__FILE__) . 'client/orderitem.js', ['jquery']);

    wp_enqueue_script('mainbag', plugin_dir_url(__FILE__) . 'client/mainbag.js', ['jquery']);
    $url = admin_url( 'admin-ajax.php' );
    wp_localize_script('mainbag', 'bagParams', ['url' => $url]); //THIS WORKS
}

add_shortcode('orderitem', "shortcode_orderitem");

add_action( 'wp_enqueue_scripts', 'enqueue_general_scripts' );

Is there some fundamental reason why you can't use wp_localize_script directly within a shortcode like that? Am I missing something else? Is there a way round it? Thanks in advance!

2
  • Have you tried setting $in_footer parameter to true when enqueueing the script? Scripts are output in wp_head by default, you can't localize a script after it's already been output to the page.
    – Milo
    Aug 21 '17 at 2:51
  • @Milo Well, I feel like an idiot now, because that worked perfectly! I was sure I'd tried it before with no success, but clearly not. Thanks, if you turn that into an Answer I'll accept it.
    – frumious
    Aug 21 '17 at 7:51
3

Default parameters for wp_enqueue_script will output the script in the wp_head function. Shortcodes typically execute later, when main content is being output.

In that case, calling wp_localize_script in the Shortcode handler will have no effect, because the script has already been output.

Setting the $in_footer parameter to true when enqueueing the script will delay script output until wp_footer, so wp_localize_script will succeed in this case.

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.