在 woocommerce 中,如何检查客户在所有订单中购买产品的次数。
我如何检查客户在他下的所有订单中可以购买某种产品的次数。
当前客户的产品购买历史记录示例:
Product one = bought 5 times
Product five = bought 1 times
Product four = bought 2 times
Product two = bought 3 times
Product three = bought 6 times
我有一个功能来检查客户是否购买了这些产品
function is_bought_items() {
$bought = false;
$_options = get_option( 'license_page_option_name' );
$ex_product_ids = $_options['ex_product_ids_warranty'];
$targeted_products= explode(",",$ex_product_ids); //id array(4,17,28,52)
// Get all customer orders
$customer_orders = get_posts( array(
'numberposts' => -1,
'meta_key' => '_customer_user',
'meta_value' => get_current_user_id(),
'post_type' => 'shop_order', // WC orders post type
'post_status' => 'wc-completed' // Only orders with status "completed"
) );
// Going through each current customer orders
foreach ( $customer_orders as $customer_order ) {
$order = wc_get_order( $customer_order );
$order_id = $order->id;
$items = $order->get_items();
// Going through each current customer products bought in the order
foreach ($items as $item) {
// Your condition related to your 2 specific products Ids
if ( in_array( $item['product_id'], $targeted_products) ) {
$bought = true; //
}
}
}
// return "true" if one the specifics products have been bought before by customer
if ( $bought ) {
return true;
}
}
在循环遍历所有项目时...我们可以节省产品购买count
在我们的数组中$item['item_meta']['_qty']
.
这是一个可能的实施示例......
function get_purchased_products() {
$products = array();
// Get all customer orders
$customer_orders = get_posts( array(
'numberposts' => - 1,
'meta_key' => '_customer_user',
'meta_value' => get_current_user_id(),
'post_type' => 'shop_order', // WC orders post type
'post_status' => 'wc-completed' // Only orders with status "completed"
) );
// Going through each current customer orders
foreach ( $customer_orders as $customer_order ) {
$order = wc_get_order( $customer_order );
$items = $order->get_items();
// Going through each current customer products bought in the order
foreach ( $items as $item ) {
$id = $item['product_id'];
// If product not in array, add it
if ( ! array_key_exists( $item['product_id'], $products ) ) {
$products[ $id ] = array(
'name' => $item['name'],
'count' => 0,
);
}
// Increment Product `count` from cart quantity
$products[ $id ]['count'] += $item['item_meta']['_qty'][0];
}
}
return $products;
}
foreach ( get_purchased_products() as $id => $product ) {
echo "<p>$id <b>$product[name]</b> bought $product[count] times</p>";
}
这输出...
70 飞行忍者购买了7次
37 快乐忍者购买了5次
19 优质购买过1次
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)