Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all orders of current user in woocommerce

I want to get all orders made by current user inside a plugin function.

I'm using this:

    function get_all_orders(){
        $customer_orders = get_posts( apply_filters( 'woocommerce_my_account_my_orders_query', array(
            'numberposts' => $order_count,
            'meta_key'    => '_customer_user',
            'meta_value'  => get_current_user_id(),
            'post_type'   => wc_get_order_types( 'view-orders' ),
            'post_status' => array_keys( wc_get_order_statuses() )
        ) ) );
   return $customer_orders;
  }

This works well inside theme but inside custom plugin it doesn't return anything. Am i doing something wrong? Should i call some WooCommerce class first?

like image 568
Daman Avatar asked Mar 07 '17 07:03

Daman


2 Answers

The API might have changed since the original question, but this is a lot more elegant and uses WC’s own functions:

$args = array(
    'customer_id' => $user_id
);
$orders = wc_get_orders($args);

You can use many more other $args.

like image 128
kontur Avatar answered Sep 27 '22 18:09

kontur


    if (!class_exists('WooCommerce')) :
        require ABSPATH . 'wp-content/plugins/woocommerce/woocommerce.php';
        $orders = get_all_orders();
    endif;

    function get_all_orders() {
        $customer_orders = get_posts(apply_filters('woocommerce_my_account_my_orders_query', array(
            'numberposts' => -1,
            'meta_key' => '_customer_user',
            'meta_value' => get_current_user_id(),
            'post_type' => wc_get_order_types('view-orders'),
            'post_status' => array_keys(wc_get_order_statuses())
                )));
        return $customer_orders;
    }

Try this code.

like image 33
mujuonly Avatar answered Sep 27 '22 18:09

mujuonly