Pass product object to javscript

I am getting a product object in php and I want to pass it to JavaScript.

This is the php code:

<?php

// Add custom Theme Functions here
//

//gg stands for Gear Guide
function gear_guide_product_view( $atts ) {

//Get Ids from shortcode
$gg_attributes = shortcode_atts( array(
‘id’ => ‘0’
), $atts );

$gg_products_ids = Array();
$gg_products = Array();

//Push ID’s into array
if ( strpos( $gg_attributes[‘id’], ‘,’ ) !== false ) {
echo ‘Multiple ID’s!’;
$gg_products_ids = explode( ‘,’, $gg_attributes[‘id’] );
} else {
echo ‘Just one Id!’;
$gg_products_ids[] = $gg_attributes[‘id’];
}
echo var_dump($gg_products_ids);

//Get product by ID’s
foreach ( $gg_products_ids as $gg_product_id ) {
$gg_product = trim( $gg_product_id, ‘ ‘ );
array_push($gg_products, wc_get_product( $gg_product ));
}
echo var_dump( $gg_products );
wp_register_script( ‘load_product_info’ , ‘/wp-content/themes/flatsome-child/js/test.js’ , array( ‘jquery’ ) );
wp_enqueue_script( ‘load_product_info’ );
wp_localize_script( ‘load_product_info’ , ‘products’ , $gg_products);
}

add_action( ‘woocommerce_loaded’, ‘my_function_with_wc_functions’ );

add_shortcode( ‘fsg’ , ‘gear_guide_product_view’ );

And this is my JavaScript:

function load_product_info() {
console.log(products);
}
load_product_info();

When I am echoing gg_products the variable looks good but in the console.log I am getting an array containing two empty objects.

Does anyone sees why is it happening?

If more information is needed tell me and I will do my best to provide it.

Thanks!

Read more here:: Pass product object to javscript

Leave a Reply

Your email address will not be published. Required fields are marked *