WooCommerce 教程:如果产品在购物车中,如何以编程方式应用优惠券

WooCommerce 教程:如果产品在购物车中,如何以编程方式应用优惠券

这是巨大的 认为它是一个不错的圣诞礼物。我可能会收取您的 $$$在您的网站上实现这一点… 所以如果这适用于您

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:如果产品添加到购物车,如何以编程方式添加优惠券

如何添加此代码?

1 、您可以将 PHP 代码片段放置在主题或子主题的 functions.php 文件的底部(如果是 CSS 代码,请添加到子主题的 style.css 文件底部)修改之前建议先备份原始文件,若出现错误请先删除此代码。

2 、 WordPress 4.9 后改进了主题编辑器,对于 CSS 代码也可打开网站前台编辑器的【自定义】,复制代码添加到自定义 css 中。

此代码是否可用?

如需帮助或是您有更好的方案想分享?请到薇晓朵 WooCommerce 中文论坛留言告知,我们希望可以帮到更多国内的 WooCommerce 用户也希望您的参与。

文章没看懂?代码不会用?需要帮助您可以去论坛提问自助服务台

作者阿呆

每当你飞起,就是一道彩虹.