localize_script but data changes dependent on product ID
I currently have this code in my functions.php
file.
$dataToBePassed = array();
add_action( 'wp_enqueue_scripts', function() {
$handle = 'three-d-scripts';
$src = get_stylesheet_directory_uri() . '/src/scripts/three-d-scripts.js';
$deps = [];
$version = '1.0.0';
wp_enqueue_script( $handle, $src, $deps, $version, true );
} );
wp_localize_script( 'three-d-scripts', 'php_vars', $dataToBePassed );
What I am wanting to do is change the contents of dataToBePassed
dependent on the product ID of the currently view products is this possible?
I have tried,
global $product; $product-get_id();
but this returns NULL as does,
global $post; $post-ID;
What I was hoping to achieve is something this,
global $product;
$product_id = $product-get_id();
$dataToBePassed = array();
add_action( 'wp_enqueue_scripts', function() {
$handle = 'three-d-scripts';
$src = get_stylesheet_directory_uri() . '/src/scripts/three-d-scripts.js';
$deps = [];
$version = '1.0.0';
wp_enqueue_script( $handle, $src, $deps, $version, true );
} );
switch($product_id) {
case 1:
//do something
break;
case 2:
//do something
break;
default:
//do something
break;
}
wp_localize_script( 'three-d-scripts', 'php_vars', $dataToBePassed );
Any ideas how I can get the woocommerce product ID so I can switch over it?
Topic woocommerce-offtopic wp-localize-script functions wp-enqueue-script Wordpress
Category Web