woocommerce如何檢查最近一年產品價格爲0時顧客購買產品的次數。爲了達到這個目的,我嘗試了下面的代碼並單獨得到答案,結果並不是按產品名稱或ID來縮短。請幫助我如何縮短它們。過去一年中客戶購買產品的次數
這裏是
//Check if bought it in last one year and the number of quantity
function customer_bought_qty(){
//get the value of targeted product
$_options = get_option('license_page_option_name');
$ex_product_ids = $_options['ex_product_ids_warranty'];
$target_products = explode(",",$ex_product_ids); //array(18,63,85)
// 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"
'date_query' => array(
array(
'column' => 'post_date_gmt',
'after' => '1 year ago',
)
)
));
// Going through each orders for current customer
foreach ($customer_orders as $customer_order) {
$order = wc_get_order($customer_order);
$order_id = $order->id;
$items = $order->get_items();
$subtotal = $order->get_subtotal(); //to check how many free item bought
//Loop trough the order items and see if it is a product we need to cehck
foreach($items as $item) {
if($subtotal== 0 && in_array($item['product_id'], $target_products)) {
$_product_id = $item['product_id'];
$_product_qty = $item['qty'];
if(isset ($_product_id)){
echo '('. get_the_title($_product_id). ')# You bought '.$_product_qty.' Times<br>';
}
}
}
}
}
輸出看起來
(Product 2)# You bought 1 Times
(Product 1)# You bought 1 Times
(Product 1)# You bought 1 Times
(Product 2)# You bought 1 Times
(Product 1)# You bought 1 Times
(Product 2)# You bought 1 Times
(Product 1)# You bought 1 Times
(Product 2)# You bought 1 Times
代碼,但我需要的結果應該看起來像
(Product 2)# You bought 4 Times
(Product 1)# You bought 4 Times
我對wordpress並不是很熟悉| woocommerce,但使用sql和'GROUP BY'產品不會更容易嗎? –
@VitaliiStrimbanu可能是可能的,但它們不在同一張表中並且難以理解如何獲得 – Firefog