0
votes

i'm creating a new custom plugin and need to retrieve all woocommerce orders

i tried to use : wc_get_orders() function to retrieve all woocommerce orders but i got

Uncaught Error: Call to undefined function wc_get_orders()

and did this :

require_once '../woocommerce/includes/wc-order-functions.php'; 

but i got :

require_once(../woocommerce/includes/wc-order-functions.php): failed to open stream: 

how i can retrieve all woocommerce orders

1
Take a look at: github.com/woocommerce/woocommerce/wiki/…. A hint: "Too few arguments to function wc_get_orders(), 0 passed in and exactly 1 expected". Another hint: $orders = wc_get_orders( array( 'customvar' => 'somevalue' ) );7uc1f3r
thanks for assistants i tried to use and got this error $query = new WC_Order_Query( array( 'limit' => 10, 'orderby' => 'date', 'order' => 'DESC', 'return' => 'ids', ) ); $orders = $query->get_orders(); Uncaught Error: Class 'WC_Order_Query' not found ... is there any include or use i should to do ?Mohamed
The code itself works, however, the information that is missing from your question is from where and how you apply this code. If you added the code into functions.php it should work without any problems. So it seems that the problem is not with the code but with its use7uc1f3r
i'm creating a custom plugin , and need to list all ordersMohamed

1 Answers

2
votes

WooCommerce already provided API to get all orders https://example.com/wp-json/wc/v3/orders

For more details please see the documentation


If you want function based instead of REST API then, please do like this:

You should call your order function into the action hook woocommerce_after_register_post_type to work properly. So please enclose your function call like this:

add_action(
    'woocommerce_after_register_post_type', 
    function() {
        $orders = wc_get_orders( array( 'numberposts' => -1 ) );
        var_dump( $orders );
    }
);

Then you can loop through the object and fetch all the necessary details for e.g.

foreach ( $orders->get_items() as $item_id => $item ) {
   $product_id = $item->get_product_id();
   $variation_id = $item->get_variation_id();
   $product = $item->get_product();
   $name = $item->get_name();
   $quantity = $item->get_quantity();
   $subtotal = $item->get_subtotal();
   $total = $item->get_total();
   $tax = $item->get_subtotal_tax();
   $taxclass = $item->get_tax_class();
   $taxstat = $item->get_tax_status();
   $allmeta = $item->get_meta_data();
   $somemeta = $item->get_meta( '_whatever', true );
   $type = $item->get_type();
}

For more details please check this article.