2017-05-25 108 views
1

我想顯示自定義的日期後的產品銷售總額後:WooCommerce展示產品總銷售額的自定義在前端一個日期

我有這樣的代碼,但我想將其自定義爲顯示自定義後,僅銷售總額日期例如05/26/2016

function total_sales() 
{ 
    global $product; 
    $units_sold = get_post_meta(206, 'total_sales', true); 
    echo '<p>' . sprintf(__('Units Sold: %s', 'woocommerce'), $units_sold) . '</p>'; 
} 

回答

2

total_sales持有的所有時間的總銷售數量,因此你需要 寫自定義查詢得到具體出售日期之間的數。

//woocommerce get total sale count of a product after a specific data 
function wh_get_total_sold_by_product_id($date_from, $product_id) 
{ 
    global $wpdb; 
    $date_to = date('Y-m-d'); 

    $sql = " 
    SELECT COUNT(*) AS sale_count 
    FROM {$wpdb->prefix}woocommerce_order_items AS order_items 
    INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS order_meta ON order_items.order_item_id = order_meta.order_item_id 
    INNER JOIN {$wpdb->posts} AS posts ON order_meta.meta_value = posts.ID 
    WHERE order_items.order_item_type = 'line_item' 
    AND order_meta.meta_key = '_product_id' 
    AND order_meta.meta_value = %d 
    AND order_items.order_id IN (
     SELECT posts.ID AS post_id 
     FROM {$wpdb->posts} AS posts 
     WHERE posts.post_type = 'shop_order' 
      AND posts.post_status IN ('wc-completed','wc-processing') 
      AND DATE(posts.post_date) BETWEEN %s AND %s 
    ) 
    GROUP BY order_meta.meta_value"; 

    return $wpdb->get_var($wpdb->prepare($sql, $product_id, $date_from, $date_to)); 
} 

代碼放在functions.php文件的活躍兒童主題(或主題)的。或者也可以在任何插件php文件中使用。

用法

//$count = wh_get_total_sold_by_product_id($my_custom_date, $product_id); 
$count = wh_get_total_sold_by_product_id('2016-05-26', 56); 

請注意:所有日期都在Y-m-d格式。

守則測試和工程。

希望這會有所幫助!

+0

Thxs了很多!作品 – alfredo49

相關問題