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.
wc_get_orders()
, 0 passed in and exactly 1 expected". Another hint:$orders = wc_get_orders( array( 'customvar' => 'somevalue' ) );
– 7uc1f3rfunctions.php
it should work without any problems. So it seems that the problem is not with the code but with its use – 7uc1f3r