[WooCommerce] 取得商品關聯訂單的方法

本篇文章更新時間:2024/04/04
如有資訊過時或語誤之處,歡迎使用 Contact 功能通知。
一介資男的 LINE 社群開站囉!歡迎入群聊聊~
如果本站內容對你有幫助,歡迎使用 BFX Pay 加密貨幣新台幣 贊助支持。


WooCommerce 內建從訂單去找到商品、查詢顧客最新一筆訂單 wc_get_customer_last_order 又或是查詢顧客是否有買過某一款商品 wc_customer_bought_product 都算常用的關聯查詢資料的方法。

但就在前天,突然想到:「那從商品去找有消費過的訂單?」

目前似乎是沒有內建做法了!

所以來筆記下找到的方法:

WooCommerce 8+ (支援 HPOS 模式)

function get_orders_ids_by_product_id( $product_id ) {
    global $wpdb;
    // HERE Define the orders status to include IN (each order status always starts with "wc-")
    $orders_statuses = array('wc-completed', 'wc-processing', 'wc-on-hold');
    // Convert order statuses array to a string for the query
    $orders_statuses = "'" . implode("', '", $orders_statuses) . "'";
    // The query
    return $wpdb->get_col( $wpdb->prepare("
        SELECT DISTINCT opl.order_id
        FROM {$wpdb->prefix}wc_order_product_lookup opl,
             {$wpdb->prefix}wc_orders o
        WHERE  opl.order_id = o.id
        AND o.type = 'shop_order'
        AND o.status IN ( {$orders_statuses} )
        AND ( opl.product_id = %d OR opl.variation_id = %d )
        ORDER BY opl.order_item_id DESC;", intval($product_id), intval($product_id) ) 
    );
}

WooCommerce 2.5+ (支援傳統模式)

function get_orders_ids_by_product_id( $product_id ) {
    global $wpdb;
    // HERE Define the orders status to include IN (each order status always starts with "wc-")
    $orders_statuses = array('wc-completed', 'wc-processing', 'wc-on-hold');
    // Convert order statuses array to a string for the query
    $orders_statuses = "'" . implode("', '", $orders_statuses) . "'";
    // The query
    return $wpdb->get_col( $wpdb->prepare("
        SELECT DISTINCT woi.order_id
        FROM {$wpdb->prefix}woocommerce_order_itemmeta woim, 
             {$wpdb->prefix}woocommerce_order_items woi, 
             {$wpdb->prefix}posts 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 IN ( '_product_id', '_variation_id' )
        AND woim.meta_value = %d
        ORDER BY woi.order_item_id DESC;", intval($product_id) ) 
    );
}

方法來源: Get all Orders IDs from a product ID in Woocommerce (+ HPOS)

從找到的參考資料來看,這需求七年以上了。其實想想可以運用的功能也不奇怪,像是:

  • 「最近哪些人購買過此商品」的提示(可能很多商城是假的資料,但這做法可以是真的!)
  • 「其他人還有買什麼?」的提示。沒有 AI 介入前,這樣去找資料也是滿直覺的。

參考資料:

後話

Woo v8.2 後的 HPOS 機制是真的不錯。但就是以寫外掛或整合服務來看。真的好多要跟著重寫啊~

本篇筆記的方法就是一個「內建還沒有提供」的一種資料庫指令操作方式。

如果某天又做了資料表上的改版,也是會要大改寫一番。


Share:

作者: Chun

資訊愛好人士。主張「人人都該為了偷懶而進步」。期許自己成為斜槓到變進度條 100% 的年輕人。[///////////____36%_________]

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *


文章
Filter
Apply Filters
Mastodon