How to get categories from an order at checkout in WooCommerce?

I am want to get the category of the items in the cart at the checkout in WooCommerce. I want to extract it and then place it in a field in my custom checkout.

I’m using WooCommerce MultiStep Checkout Wizard premium plugin and a specific hook:

Read More
add_action('woocommerce_multistep_checkout_before_order_info', 'destinationStep');

I’m a little lost and can’t find much documentation for what I need to use to get it.

I’m trying to just get items to appear but I just get an empty array.

$order = new WC_Order( $order_id );
$items = $order->get_items(); 
var_dump($items);

Related posts

Leave a Reply

1 comment

  1. You could try first with your approach new WC_Order( $order_id );, this way:

    function destinationStep( $order_id )
    
        global $woocommerce; 
    
        $order = new WC_Order( $order_id );
        $items = $order->get_items(); 
        // echo var_dump($items);
    
        //----
        foreach ($items as $key => $item) {
            $product_name = $item['name'];
            $product_id = $item['product_id'];
            $terms = get_the_terms( $product_id, 'product_cat' );
            // echo var_dump($terms);
    
            foreach ( $terms as $term ) {
                // Categories by slug
                $product_cat_slug= $term->slug;
            }
        }
    
    add_action('woocommerce_multistep_checkout_before_order_info', 'destinationStep', 10, 1);
    

    If it still doesn’t work try with new WC_Order($post->ID) approach:

    function destinationStep()
    
        global $woocommerce, $post; 
    
        $order = new WC_Order($post->ID);
        $items = $order->get_items(); 
        // echo var_dump($items);
    
        //----
        foreach ($items as $key => $item) {
            $product_name = $item['name'];
            $product_id = $item['product_id'];
            $terms = get_the_terms( $product_id, 'product_cat' );
            // echo var_dump($terms);
    
            foreach ( $terms as $term ) {
                // Categories by slug
                $product_cat_slug= $term->slug;
            }
        }
    
    add_action('woocommerce_multistep_checkout_before_order_info', 'destinationStep');
    

    Update – After some thought:

    You can’t get the order Id for `’post_type’ => ‘shop_order’, because it doesn’t exist yet. This order ID is generated when customer submit the order, but not before on checkout page.
    So in this case, it’s normal to get an empty array.