Search code examples
phpwoocommercehook-woocommerce

Woocommerce function get_items() return empty array


I want to get all product from order and I need work with this product list in JS script.

I have something like this in function.php:

add_action( 'wp_head', 'function_after_order' );
function function_after_order() {
    if ( ! is_wc_endpoint_url('order-received') ) return;
    global $wp;

    // If order_id is defined
    if ( isset($wp->query_vars['order-received']) && absint($wp->query_vars['order-received']) > 0 ) :

    $order_id = absint($wp->query_vars['order-received']); // The order ID
    $order = wc_get_order($order_id ); // The order object
    $items = json_encode($order->get_items());
    ?>
      
    <script type="text/javascript">
        console.log(<?php echo $order ?>);
        console.log(<?php echo $items ?>);
    </script>
    <?php
    endif;
}

$order displays the entire object beautifully, but $items displays an empty object {37: {…}} with the product ID number without any other information.

In what way is it possible to work with the products in the order?

Thanks


Solution

  • This won't work because your $items is not a classic array of elements, instead it contains protected values that you need to get properly using the get_data() method.

    This is a one-liner that should work for your use case:

    $items = json_encode( array_map( function($item){ return $item->get_data(); }, $order->get_items() ) );
    

    Credit: LoicTheAztec