I am trying to access the stock_quantity, ID and SKU for woocommerce products in a php array.
I need to get the SKU to compare it against a value in my JavaScript code so that I can display the stock_quantity for the selected product and update an add to cart link with the selected product ID.
I am getting the products by creating a query that returns any product with a SKU containing the $tag variable I am passing it like this:
// Get any products with SKU that includes tag
$query = new WC_Product_Query();
$query->set( 'sku', $tag );
$products = $query->get_products();
Ideally I would like to convert this php array into a javacript array with all the nested arrays/objects in tact. This snippet will successfully log the array to the console and I can see that the array does in fact contain the products I need access to.
echo "<script>console.log(".json_encode(var_export($products, true)).");</script>";
If its not possible to simply convert the array and all the nested content into a javscript array, Im wondering if perhaps there is a way to recursively loop through the php array and push the content to a javascript array.
Any help would be greatly appreciated! This is my first stack overflow post!
CodePudding user response:
If you want to send data from php to javascript you can use such a thing.
In php:
$vars = [
'data1' => ["first" => 1, "second" => 2],
... some many proprieties
];
wp_localize_script('name_of_script', 'name_of_variables', $vars);
In javascript :
console.log(name_of_variables.data1)
Maybe the IDE will tell you that he cannot find the variable, because the variable is in PHP page. Then in javascript you can use it as you like
I hope it will be useful to you Best regards
CodePudding user response:
Unfortunately no one was albe to provide a snippet but I was able to come up with a solution, so here it is:
// Get any products with SKU that includes tag
$query = new WC_Product_Query();
$query->set( 'sku', $tag );
$products = $query->get_products();
// Initialize an empty array
$products_arr = array();
// Loop through products
foreach($products as $product){
// Create an empty object for each product
$prod = new stdClass();
// Set get product data and add to object
$prod->stock_quantity = $product->get_stock_quantity();
$prod->sku = $product->get_sku();
$prod->id = $product->get_id();
$prod->price = $product->get_price();
// Push product object with data to array
array_push($products_arr, $prod);
}
// Create JS var and set it to the array of objects
echo "<script>var ticketsBySku = ".json_encode($products_arr).";</script>";
Now I have a js variable that I can access anywhere in my code that contains the content from my woocommerce products query (php array)
Hope that helps somebody!