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!
$in_footerparameter totruewhen enqueueing the script? Scripts are output inwp_headby default, you can't localize a script after it's already been output to the page.