Passing product details from an order to jQuery/javascript on WooCommerce checkout

Solution:

  • woocommerce_checkout_order_processed contains not 1 but 3 arguments
  • An order usually consists of several products, so $product = wc_get_product( $order_id ); won’t work

 

So you get:

function action_woocommerce_checkout_order_processed( $order_id, $posted_data, $order ) {
    // Initialize
    $product_ids = array();
    $prices = array();
    
    // Loop through order items
    foreach ( $order->get_items() as $item_id => $item ) {
        // Get the WC_Product Object
        $product = $item->get_product();
        
        // Product ID
        $product_id = $item->get_variation_id() > 0 ? $item->get_variation_id() : $item->get_product_id();
        
        // Price
        $product_price = $product->get_price();
        
        // Push to array
        $product_ids[] = $product_id;
        $prices[] = $product_price;
    }
    ?>
    <script>
    jQuery(function($) {
        // jQuery variables
        var product_ids = <?php echo json_encode( $product_ids ); ?>;
        var prices = <?php echo json_encode( $prices ); ?>;
        
        // Log
        console.log( product_ids );
        console.log( prices );
    });
    </script>
    <?php
}