php查订单有多少商品,php-从产品ID获取所有订单ID

如何获得具有按产品ID的订单ID的数组?

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

我知道如何通过MySQL执行此操作,但是有没有办法通过WP_Query函数执行此操作?

解决方法:

UPDATED: Changed the SQL query to "SELECT DISTINCT" instead of just "SELECT" to avoid duplicated Order IDs in the array (then no need of array_unique() to filter duplicates…).

据我所知,使用WP查询是不可能的,但是使用WordPress class wpdb可以轻松地做到这一点,包括SQL查询.

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

因此,这是将完成此工作的函数:

function retrieve_orders_ids_from_a_product_id( $product_id ) {

global $wpdb;

// Define HERE the orders status to include in <== <== <== <== <== <== <==

$orders_statuses = "'wc-completed', 'wc-processing', 'wc-on-hold'";

# Requesting All defined statuses Orders IDs for a defined product ID

$orders_ids = $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 LIKE '_product_id'

AND woim.meta_value LIKE '$product_id'

ORDER BY woi.order_item_id DESC"

);

// Return an array of Orders IDs for the given product ID

return $orders_ids;

}

此代码可以在任何php文件中找到.

此代码已经过测试,可用于WooCommerce 2.5、2.6和3.0版本

用法示例:

## 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 = retrieve_orders_ids_from_a_product_id( $product_id );

// We display the orders in a coma separated list

echo '

' . implode( ', ', $orders_ids_array ) . '

';

标签:orders,php,wordpress,woocommerce,product

来源: https://codeday.me/bug/20191013/1907669.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值