這是巨大的 認為它是一個不錯的聖誕禮物。我可能會收取您的 $$$在您的網站上實現這一點… 所以如果這適用於您

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();     }     }  }  

看看您的購物車頁面,應該看起來像這樣!

WooCommerce:如果產品添加到購物車,如何以編程方式添加優惠券


可以在哪裏添加此代碼?

您可以將 PHP 代碼片段放置在主題或子主題的 functions.php 文件的底部(如果是 CSS 代碼,請添加到主題的 style.css 文件底部),修改之前建議先備份原始文件,若出現錯誤請先刪除此代碼。


這段代碼是否正常可用?

或者是您有更好的解決方案想要分享?請到薇曉朵 WooCommerce 中文論壇留言告知,我們希望可以幫到更多國內的 WooCommerce 用户也希望您的參與。


需要關於 WooCommerce 的幫助?

請觀看我們提供的免費視頻教程或到薇曉朵 WooCommerce 中文論壇提問,會有專業技術團隊提供相關幫助。