之前我們介紹了一些魔術 WooCommerce 內建功能 「 wc_customer_bought_product 」 – 自動地使用一行 PHP,您可以瞭解使用者是否已經購買了產品 ID 。
但是,當構建我的新的 #BloomerArmada 部分時,我不得不知道使用者是否在過去 365 天內購買了產品 ID … 所以我重寫了這個功能,改變了它的名字,並新增了一點編輯 – 容易的笨蛋!

PHP Snippet:檢查使用者是否在最近 365 天內購買了產品 ID
/** * @snippet New version of "wc_customer_bought_product" function (last 365 days) * @sourcecode https://businessbloomer.com/?p=21885 * @author Rodolfo Melogli * @compatible WC 2.6.14, WP 4.7.2, PHP 5.5.9 */ function wc_customer_bought_product_last_year( $customer_email, $user_id, $product_id ) { global $wpdb; $customer_data = array( $user_id ); $customer_data[] = $customer_email; $customer_data = array_map( 'esc_sql', array_filter( array_unique( $customer_data ) ) ); if ( sizeof( $customer_data ) == 0 ) { return false; } $result = $wpdb->get_col( " SELECT im.meta_value FROM {$wpdb->posts} AS p INNER JOIN {$wpdb->postmeta} AS pm ON p.ID = pm.post_id INNER JOIN {$wpdb->prefix}woocommerce_order_items AS i ON p.ID = i.order_id INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS im ON i.order_item_id = im.order_item_id WHERE p.post_status IN ( 'wc-completed', 'wc-processing' ) AND p.post_date > '" . date('Y-m-d', strtotime('-365 days')) . "' AND pm.meta_key IN ( '_billing_email', '_customer_user' ) AND im.meta_key IN ( '_product_id', '_variation_id' ) AND im.meta_value != 0 AND pm.meta_value IN ( '" . implode( "','", $customer_data ) . "' ) " ); $result = array_map( 'absint', $result ); return in_array( absint( $product_id ), $result ); }
現在,您的 functions.php 中存在 「wc_customer_bought_product_last_year」,您可以在程式碼段或簡碼中使用它 與 「wc_customer_bought_product」 唯一的主要區別就是這一行:
AND p.post_date > '" . date('Y-m-d', strtotime('-365 days')) . "'
如何新增此程式碼?
1 、您可以將 PHP 程式碼片段放置在主題或子主題的 functions.php 檔案的底部 (如果是 CSS 程式碼,請新增到子主題的 style.css 檔案底部) 修改之前建議先備份原始檔案,若出現錯誤請先刪除此程式碼。
2 、 WordPress 4.9 後改進了主題編輯器,對於 CSS 程式碼也可開啟網站前臺編輯器的 【自定義】,複製程式碼新增到自定義 css 中。
此程式碼是否可用?
如需幫助或是您有更好的方案想分享?請到薇曉朵 WooCommerce 中文論壇留言告知,我們希望可以幫到更多國內的 WooCommerce 使用者也希望您的參與。