Seb G
Seb G

Reputation: 671

Conditional checkout fee based off of checkbox value- WooCommerce

I have a checkbox for a custom user meta field in the billing address section of the checkout process. I'm trying to dynamically add a fee to the checkout total when the checkbox is checked, or in this case, == '1'.

My Attempt:

add_action( 'woocommerce_cart_calculate_fees','ups_yes_no_fee', 43, 1 );
function ups_yes_no_fee( $wc_cart ) {
    global $woocommerce;

    if($_POST['billing_ups_yn'] == '1'){
        //echo 'checked';
        $woocommerce->cart->add_fee( __('Own Account Shipping', 'woocommerce'), 20 );

    }
}

It'll apply the fee if I remove the "if" statement so I'm guessing this is the wrong way to apply a fee based off of a checkout field. How can I accomplish this?

Upvotes: 0

Views: 1148

Answers (1)

Seb G
Seb G

Reputation: 671

I found the answer here.

Here is the solution to my problem:

add_action( 'wp_footer', 'woocommerce_add_ups_y_n', 357 );
function woocommerce_add_ups_y_n() {
    if (is_checkout()) {
    ?>
    <script type="text/javascript">
    jQuery( document ).ready(function( $ ) {
        jQuery('#billing_ups_yn').click(function(){
            jQuery('body').trigger('update_checkout');
        });
    });
    </script>
    <?php
    }
}
add_action( 'woocommerce_cart_calculate_fees', 'woo_add_cart_ups_y_n_fee', 43, 1);
function woo_add_cart_ups_y_n_fee( $cart ){
        if ( ! $_POST || ( is_admin() && ! is_ajax() ) ) {
        return;
    }

    if ( isset( $_POST['post_data'] ) ) {
        parse_str( $_POST['post_data'], $post_data );
    } else {
        $post_data = $_POST;
    }

    if (isset($post_data['billing_ups_yn'])) {
        $extracost = 25;
        WC()->cart->add_fee( 'Own UPS Account', $extracost );
    }

}

(put in child theme's functions.php file)

Upvotes: 2

Related Questions