WordPress: ottenere i dati di tutti gli ordini completati di WooCommerce

WordPress: ottenere i dati di tutti gli ordini completati di WooCommerce

Esiste una soluzione molto semplice per ottenere in WordPress i dati di tutti gli ordini completati di WooCommerce.

Possiamo creare la seguente funzione di utility:


<?php

function my_get_orders() {
    $args = array(
     'post_type'   => 'shop_order',
     'post_status' => 'wc-completed',
     'numberposts' => -1
     );
     $output = array();
     $orders = get_posts( $args );

     if( !empty( $orders ) ) {
         foreach( $orders as $order ) {

             $order = new WC_Order( $order->ID );


             $order_data = $order->get_data();
             $items = $order->get_items();

             $output_item = array();

             $date = $order_data['date_created']->date( 'Y-m-d H:i:s' );

             // Ottengo la percentuale IVA

             $vat = '';
             $tax = new WC_Tax();
             $rates = $tax->find_rates( $order_data['billing'] );
             foreach( $rates as $rate ) {
                 $label = $rate['label'];
                 if( strstr( $label, 'VAT' ) !== false ) {
                     $str = str_replace( array( '(', ')', 'VAT' ), '', $label );
                     $vat = trim( $str );
                 }
             }


             $output_item['id'] = $order->ID;
             $output_item['date'] = $date;
             $output_item['vat'] = $vat;
             $output_item['currency'] = $order_data['currency'];
             $output_item['billing'] = $order_data['billing'];
             $output_item['shipping'] = $order_data['shipping'];
             $output_item['items'] = array();

             foreach( $items as $key => $values ) {
               $item_data = $values->get_data();
               $product_id = $item_data['product_id'];
               $prod = new WC_Product( $product_id );
               $line_total = $item_data['total'];
               $line_total_tax = $item_data['total_tax'];

               $it = array();
               $it['sku'] = $prod->get_sku();
               $it['description'] = $item_data['name'];
               $it['quantity'] = $item_data['quantity'];
               $it['price'] = $prod->get_price();
               $it['total'] = $line_total;
               $it['tax'] = $line_total_tax;

               $output_item['items'][] = $it;
             }

             $output_item['total'] = $order->get_total();
             $output_item['total_partial'] = ( $order->get_total() - $order->get_total_tax() );
             $output_item['total_vat'] = round( $order->get_total_tax(), 2 );

             $output[] = $output_item;

         }
     }
     return $output;
}

Torna su