如何获得具有按产品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 ofarray_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;
}
此代码已经过测试,可用于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 '<p>' . implode( ', ', $orders_ids_array ) . '</p>';
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。