Tuesday, February 14, 2023

Get completed orders count for a specific user with a specific product in Woocommerce

Get completed orders count for a specific user with a specific product in Woocommerce:

Code:

function get_total_product_completed_order_for_a_specific_user() {
    $product_slug = 'product-slug';
    $product_obj = get_page_by_path($product_slug, OBJECT, 'product');

    $pid = 0;
    if (!empty($product_obj)) {
        $pid = $product_obj->ID;
    }

    // Get all customer orders
    $customer_orders = get_posts(
        array(
            'numberposts' => -1,
            'meta_key'    => '_customer_user',
            'orderby'     => 'date',
            'order'       => 'DESC',
            'meta_value'  => get_current_user_id(),
            'post_type'   => wc_get_order_types(),
            'post_status' => array_keys(wc_get_order_statuses()),
            'post_status' => array('wc-completed'),
        )
    );

    $Order_Array = [];
    $apid_counter = 0;
    foreach ($customer_orders as $customer_order) {
        $orderq        = wc_get_order($customer_order);

        $items = $orderq->get_items();

        foreach ( $items as $item ) {
            $product_id = $item->get_product_id();
            if ($pid == $product_id) {
                $apid_counter++;
            }
            break;
        }

        $Order_Array[] = [
            "ID"    => $orderq->get_id(),
            "Value" => $orderq->get_total(),
            "Date"  => $orderq->get_date_created()->date_i18n('Y-m-d'),
        ];
    }

    // return count($Order_Array);
    return $apid_counter;
}

Happy coding...



No comments:

Post a Comment

Suomen kieli (Imperfekti)

In Finnish, the imperfekti is the past tense that describes actions that happened in the past, like the English simple past (e.g., "I ...