簡體   English   中英

WooCommerce:過去 30 天最暢銷產品的自定義循環

[英]WooCommerce: Custom loop for best selling products of the last 30 days

我想展示過去 30 天最暢銷的產品。 我已經有一個顯示暢銷產品的代碼。 但這些是商店的總銷售額。 是否可以選擇將產品銷售時間限制為 30 天?

我猜元鍵total_sales不是正確的方法,對吧?

這是我當前的循環:

$args_basic = array(
    'post_type'         => 'product',
    'posts_per_page'    => 12,
    'meta_key'          => 'total_sales',
    'orderby'           => 'meta_value_num',
);

我無法測試以下內容,但乍一看它應該在壁虎上工作。

  • 我們通過wc_get_ordersdate_after參數查詢上個月的訂單。
  • 然后我們檢索每個訂單商品的 ID 並將它們推送到一個新的Array中。
  • 最后,我們可以使用array_count_values()來計算每個 ID 出現的次數。
<?php

add_action( 'init', 'wpso_67421248' );
  
function wpso_67421248() {

   $orders = wc_get_orders(
        array(
            'limit' => -1,
            'status' => array_map( 'wc_get_order_status_name', wc_get_is_paid_statuses() ),
            'date_after' => date( 'Y-m-d', strtotime( '-1 month' ) ),
            'return' => 'ids',
        )
   );

   $identifiers = array();

   foreach ( $orders as $order ) {

        $items = wc_get_order( $order )->get_items();

        foreach ( $items as $item ) {

            array_push( $identifiers, $item->get_product_id() );

        };

    };

    var_dump( rsort( array_count_values( $identifiers ) ) );

};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM