Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

125
Visualizações
How do I convert a nested array of Woocommerce products into a Javascript object?

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!

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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!

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda