获取产品的所有订单

获取产品的所有订单

本文介绍了Woocommerce:获取产品的所有订单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Woocommerce API 中,我看到了一个方法 wc_get_orders

In the Woocommerce API I see a method wc_get_orders

WooCommerce 订单功能

在上述参数中,我没有看到可以提供产品 ID 或对象来限制仅针对该特定产品的订单结果的参数.

In the mentioned args I do not see an argument in which I could provide a product ID or Object to limit order results only for that specific product.

有什么方法可以过滤特定产品的订单?

Is there a way I could filter orders only for specific products?

我需要使用这个方法,因为一些参数是必要的

I need to use this method since some arguments are necessary

推荐答案

已编辑此功能不存在,但可以构建.因此,下面的函数将返回给定产品 ID 的所有订单 ID 的数组,从而进行正确的 SQL 查询:

EditedThis function doesn't exist, but it can be built. So the function below will return an array of all orders IDs for a given product ID, making the right SQL query:

/**
 * Get All orders IDs for a given product ID.
 *
 * @param  integer  $product_id (required)
 * @param  array    $order_status (optional) Default is 'wc-completed'
 *
 * @return array
 */
function get_orders_ids_by_product_id( $product_id, $order_status = array( 'wc-completed' ) ){
    global $wpdb;

    $results = $wpdb->get_col("
        SELECT order_items.order_id
        FROM {$wpdb->prefix}woocommerce_order_items as order_items
        LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta as order_item_meta ON order_items.order_item_id = order_item_meta.order_item_id
        LEFT JOIN {$wpdb->posts} AS posts ON order_items.order_id = posts.ID
        WHERE posts.post_type = 'shop_order'
        AND posts.post_status IN ( '" . implode( "','", $order_status ) . "' )
        AND order_items.order_item_type = 'line_item'
        AND order_item_meta.meta_key = '_product_id'
        AND order_item_meta.meta_value = '$product_id'
    ");

    return $results;
}

USAGE 1(对于给定的产品 ID 37 和默认的已完成订单状态):

USAGE 1 (for a given product ID 37 and default Completed orders status):

$orders_ids = get_orders_ids_by_product_id( 37 );

// The output (for testing)
print_r( $orders_ids );

USAGE 2(对于给定的产品 ID 37一些定义的订单状态):

USAGE 2 (for a given product ID 37 and some defined orders statuses):

// Set the orders statuses
$statuses = array( 'wc-completed', 'wc-processing', 'wc-on-hold' );

$orders_ids = get_orders_ids_by_product_id( 37, $statuses );

// The output (for testing)
print_r( $orders_ids );

代码位于活动子主题(或主题)的 function.php 文件或任何插件文件中.

此代码已经过测试且有效.

This code is tested and works.

这篇关于Woocommerce:获取产品的所有订单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 04:46