mardi 24 août 2021

Can I use PHP Switch Statement On Ajax Form?

enter image description hereI have very little programming experience. I have a Woocommerce plugin installed that adds subscription options to the cart as can be seen from the image. The person selects the subscription length they desire. When I inspect the code it shows the radio button to be named "convert_to_sub" and the values change from 0 when a one time purchase is made to "1_week_2", "1_week_3", "1_week_4" and so on depending on how I configure the subscriptions. I want to dynamically apply a pre-created coupon code depending on which subscription option they choose. However, this code only runs when the customer initially clicks on the page. It assigns the coupon code that is initially defined, but the IF SWITCH does not execute. It's an Ajax form. Is this a valid way of doing this? I'm am adding the function using the Snippets plugin.


add_action( 'woocommerce_before_cart', 'apply_matched_coupons' );

function apply_matched_coupons() {

$coupon_code = 'coupon_cat5_3';
$convert_to_sub = 0;
    
if(isset($_POST["convert_to_sub"]) ) {      
    switch ($_POST["convert_to_sub"]) {
       case "1_week_2":
            $coupon_code = 'coupon_cat5_2';             
             break;
        case "1_week_3":
            $coupon_code = 'coupon_cat5_3';
             break;
        case "1_week_4":
            $coupon_code = 'coupon_cat5_4';
             break;
    }
}    
  

if ( WC()->cart->has_discount( $coupon_code ) ) return;

foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {

// this is your product ID
$autocoupon = array( 6700 );

if ( in_array( $cart_item['product_id'], $autocoupon ) ) {   
    WC()->cart->apply_coupon( $coupon_code );
    wc_print_notices();
}

}

}

Aucun commentaire:

Enregistrer un commentaire