jeudi 10 août 2023

Product page custom checkbox enable a percentage discount on WooCommerce cart subtotal

The goal is simple, add a checkbox to the WooCommerce Product Page. If the user checks the checkbox, a 5% discount is applied on cart subtotal.

I have checked and doubled checked the code like ten times, I just cannot figure out why it gives me the "Fatal Error".

This is the code:

add_action( 'woocommerce_after_add_to_cart_button', 'ls_automatic_discount_checbox', 10 );
function ls_automatic_discount_checbox() {
    echo '<p><label><input type="checkbox" name="apply_automatic_discount" value="1"/> Apply 5% discount to your subtotal</label></p>';
}

add_action( 'woocommerce_cart_calculate_fees', 'ls_apply_discount_on_checkbox_check', 10, 7 );
function ls_apply_discount_on_checkbox_check( $cart, $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ) {

        // makes sure that the checkbox is ticked
        if ( isset( $_POST[ 'apply_automatic_discount' ] ) && $_POST[ 'apply_automatic_discount' ] == 1 ) {        

        // if it is, check what the percentaged discount on the subtotal is
        $percent = 5;

        // if all checks out - give the discount
        if ( isset ( $percent ) && $percent > 0 ) {

        // customer gets a discount of 5% of the SUBTOTAL
        $discount = $cart->cart_contents_total * $percent / 100;
        $cart->add_fee( __('5% OFF', 'woocommerce' ) . " (" . $percent . "%)", -$discount);
    
        }
    }
}



Aucun commentaire:

Enregistrer un commentaire