這是巨大的 認為它是一個不錯的聖誕禮物。我可能會收取您的 $$$在您的網站上實現這一點… 所以如果這適用於您
1. 將特定產品添加到購物車後,創建要應用的優惠券代碼
轉到 WooCommerce /優惠券/添加新的,並決定您的優惠券代碼。例如 「freeweek」,這是稍後在 PHP 代碼片段中使用的優惠券代碼。
2. 識別您的產品 ID
轉到 WordPress /產品,並將其懸停在您要使用優惠券的產品上。無論網址欄中顯示的任何 ID,請記錄。在我們的例子中,我們將針對產品 ID =「745」 。
代碼段 [WC 2.1+]:如果產品在購物車中,則以編程方式應用優惠券
/** * @snippet How to Apply a Coupon Programmatically WooCommerce * @sourcecode https://businessbloomer.com/?p=516 * @author Rodolfo Melogli * @compatible WooCommerce 2.4.7 */ // Apply coupon programmatically add_action( 'woocommerce_before_cart', 'bbloomer_apply_matched_coupons' ); function bbloomer_apply_matched_coupons() { global $woocommerce; $coupon_code = 'freeweek'; if ( $woocommerce->cart->has_discount( $coupon_code ) ) return; foreach ($woocommerce->cart->cart_contents as $key => $values ) { // this is your product ID $autocoupon = array(745); if(in_array($values['product_id'],$autocoupon)){ $woocommerce->cart->add_discount( $coupon_code ); wc_print_notices(); } } }
代碼段 [2.1 之前的 WC]:如果產品在購物車中,則以編程方式應用優惠券
/** * @snippet How to Apply a Coupon Programmatically WooCommerce * @sourcecode https://businessbloomer.com/?p=516 * @author Rodolfo Melogli * @compatible WooCommerce 2.4.7 */ // Apply coupon programmatically add_action( 'woocommerce_before_cart', 'bbloomer_apply_matched_coupons' ); function bbloomer_apply_matched_coupons() { global $woocommerce; $coupon_code = 'freeweek'; if ( $woocommerce->cart->has_discount( $coupon_code ) ) return; foreach ($woocommerce->cart->cart_contents as $key => $values ) { // this is your product ID $autocoupon = array(745); if(in_array($values['product_id'],$autocoupon)){ $woocommerce->cart->add_discount( $coupon_code ); $woocommerce->show_messages(); } } }
看看您的購物車頁面,應該看起來像這樣!

如何添加此代碼?
1 、您可以將 PHP 代碼片段放置在主題或子主題的 functions.php 文件的底部 (如果是 CSS 代碼,請添加到子主題的 style.css 文件底部) 修改之前建議先備份原始文件,若出現錯誤請先刪除此代碼。
2 、 WordPress 4.9 後改進了主題編輯器,對於 CSS 代碼也可打開網站前台編輯器的 【自定義】,複製代碼添加到自定義 css 中。
此代碼是否可用?
如需幫助或是您有更好的方案想分享?請到薇曉朵 WooCommerce 中文論壇留言告知,我們希望可以幫到更多國內的 WooCommerce 用户也希望您的參與。