从 Woocommerce 中的产品 ID 获取所有订单 ID [英] Get all Orders IDs from a product ID in Woocommerce

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

问题描述

如何通过产品 ID 获取带有订单 ID 的数组?

How can I get an array with Order IDs by Product ID?

我的意思是收到所有显示特定产品的订单.

I mean receive all orders where specific product is presented.

我知道如何通过 MySQL 做到这一点,但是有没有办法通过 WP_Query 函数做到这一点?

I know how to do this by MySQL, but is there a way to do this by WP_Query function?

推荐答案

更新:

  • 2017 - SQL 查询更改为 "SELECT DISTINCT" 而不是 "SELECT"避免 重复 订单 ID 在数组中(然后不需要 array_unique() 过滤重复项...).

  • 2017 - SQL query changed to "SELECT DISTINCT" instead of "SELECT" to avoid duplicated Order IDs in the array (then no need of array_unique() to filter duplicates…).

2019 - 在 SQL 查询中启用产品变体类型支持

2019 - Enabled product variation type support in the SQL Query

然后您可以将其嵌入到一个自定义函数中,以 $product_id 作为参数.
您必须在其中设置订单状态您的目标.

Then you can embed this in a custom function with $product_id as argument.
You will have to set inside it, the order statuses that you are targeting.

这里是完成这项工作的函数:

So here is the function that will do the job:

function get_orders_ids_by_product_id( $product_id ) {
    global $wpdb;
    
    // Define HERE the orders status to include in  <==  <==  <==  <==  <==  <==  <==
    $orders_statuses = "'wc-completed', 'wc-processing', 'wc-on-hold'";

    # Get All defined statuses Orders IDs for a defined product ID (or variation ID)
    return $wpdb->get_col( "
        SELECT DISTINCT woi.order_id
        FROM {$wpdb->prefix}woocommerce_order_itemmeta as woim, 
             {$wpdb->prefix}woocommerce_order_items as woi, 
             {$wpdb->prefix}posts as p
        WHERE  woi.order_item_id = woim.order_item_id
        AND woi.order_id = p.ID
        AND p.post_status IN ( $orders_statuses )
        AND woim.meta_key IN ( '_product_id', '_variation_id' )
        AND woim.meta_value LIKE '$product_id'
        ORDER BY woi.order_item_id DESC"
    );
}

这段代码可以放在任何 php 文件中.

此代码经过测试,适用于 WooCommerce 2.5+、2.6+ 和 3+ 版

This code is tested and works for WooCommerce version 2.5+, 2.6+ and 3+

使用示例:

## This will display all orders containing this product ID in a coma separated string ##

// A defined product ID: 40
$product_id = 40;

// We get all the Orders for the given product ID in an arrray
$orders_ids_array = get_orders_ids_by_product_id( $product_id );

// We display the orders in a coma separated list
echo '<p>' . implode( ', ', $orders_ids_array ) . '</p>';

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆