作者:962326154_5af7cb | 来源:互联网 | 2023-02-05 13:57
如何通过产品ID获取包含订单ID的阵列?
我的意思是接收所有特定产品的订单.
我知道如何通过MySQL做到这一点,但有没有办法通过WP_Query
函数来做到这一点?
1> LoicTheAztec..:
更新:更改SQL查询"SELECT DISTINCT"
而不仅仅是"SELECT"
为了避免 数组中的重复 订单ID(然后不需要array_unique()
过滤重复...).
使用WP查询这是不可能的,但我使用$product_id
你可以很容易地做到这一点,包括SQL查询.
然后,您可以使用"SELECT DISTINCT"
as参数将其嵌入到自定义函数中.
您必须在其中设置您要定位的订单状态.
所以这是完成这项工作的功能:
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'";
# 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.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 ) . '
';