這是一個故事:我正在和我的一個自由客户合作,如果這樣的產品在購物車中,我需要在結帳中顯示某些內容 (產品特定的 「條款和條件」) 。
我一直在購物車中尋找產品,通過購物車 「循環」(foreach)(這裏例如:如果產品在購物車中以編程方式應用優惠券) 。
但正如我所説,經過一些隨機研究,我發現了另一個魔術 WooCommerce 功能:「find_product_in_cart()」 。這意味着在購物車中找到產品不需要做自定義循環或複雜的 PHP … 它是一個 「一個班輪」!

PHP 代碼段:輕鬆檢查產品 ID 是否在購物車中 – WooCommerce
/** * @snippet Check if Product ID is in the Cart - WooCommerce * @sourcecode https://businessbloomer.com/?p=72733 * @author Rodolfo Melogli * @testedwith WooCommerce 3.1.1 */ add_action('woocommerce_before_cart', 'bbloomer_find_product_in_cart'); function bbloomer_find_product_in_cart() { $product_id = 282; $product_cart_id = WC()->cart->generate_cart_id( $product_id ); $in_cart = WC()->cart->find_product_in_cart( $product_cart_id ); if ( $in_cart ) { $notice = 'Product ID ' . $product_id . ' is in the Cart!'; wc_print_notice( $notice, 'notice' ); } }
如何添加此代碼?
1 、您可以將 PHP 代碼片段放置在主題或子主題的 functions.php 文件的底部 (如果是 CSS 代碼,請添加到子主題的 style.css 文件底部) 修改之前建議先備份原始文件,若出現錯誤請先刪除此代碼。
2 、 WordPress 4.9 後改進了主題編輯器,對於 CSS 代碼也可打開網站前台編輯器的 【自定義】,複製代碼添加到自定義 css 中。
此代碼是否可用?
如需幫助或是您有更好的方案想分享?請到薇曉朵 WooCommerce 中文論壇留言告知,我們希望可以幫到更多國內的 WooCommerce 用户也希望您的參與。