简体   繁体   中英

Display a checkbox that add a fee in Woocommerce checkout page

In Woocommerce checkout page, I'am trying to add a check box on checkout page

I have referred to these articles

woocommerce custom checkout field to add fee to order ajax

Checkbox field that add / remove a custom fee in WooCommerce

Add a checkout checkbox field that enable a percentage fee in Woocommerce

add_action( 'woocommerce_review_order_before_order_total', 'checkout_shipping_form_packing_addition', 20 );
function checkout_shipping_form_packing_addition( ){
echo '<tr class="packing-select"><th>';
woocommerce_form_field( 'add_gift_box', array(
    'type'          => 'checkbox',
    'class'         => array('add_gift_box form-row-wide'),
    'label'         => __('Hỗ trợ cài đặt'),
    'placeholder'   => __(''),
    ));
echo '</th><td>';}

add_action( 'wp_footer', 'woocommerce_add_gift_box' );
function woocommerce_add_gift_box() {
if (is_checkout()) {
?>
<script type="text/javascript">
jQuery( document ).ready(function( $ ) {
    $('#add_gift_box').click(function(){
        jQuery('body').trigger('update_checkout');
    });
});
</script>
<?php
}}
add_action( 'woocommerce_cart_calculate_fees', 'woo_add_cart_fee' );
function woo_add_cart_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; // fallback for final checkout (non-ajax)
}

if (isset($post_data['add_gift_box'])) {
    $sl = WC()->cart->get_cart_contents_count();
    $extracost = 50000 * $sl; // not sure why you used intval($_POST['state']) ?
    WC()->cart->add_fee( 'Hỗ trợ cài đặt x '.$sl.'', $extracost );
}}
add_filter( 'woocommerce_form_field' , 'remove_order_comments_optional_fields_label', 10, 4 );
function remove_order_comments_optional_fields_label( $field, $key, $args, $value ) {
// Only on checkout page for Order notes field
if( 'add_gift_box' === $key && is_checkout() ) {
    $optional = '&nbsp;<span class="optional">(' . esc_html__( 'optional', 'woocommerce' ) . ')</span>';
    $field = str_replace( $optional, '', $field );
}
return $field;
}

It does not work as I would like. What I am doing wrong?

Any help is appreciated.

You really need to use Wordpress Ajax with WC_sessions to make it work like in " Add a checkout checkbox field that enable a percentage fee in Woocommerce " answer thread.

Here is your revisited code:

// Display the custom checkbow field in checkout
add_action( 'woocommerce_review_order_before_order_total', 'fee_installment_checkbox_field', 20 );
function fee_installment_checkbox_field(){
    echo '<tr class="packing-select"><th>';

    woocommerce_form_field( 'installment_fee', array(
        'type'          => 'checkbox',
        'class'         => array('installment-fee form-row-wide'),
        'label'         => __('Support installation'),
        'placeholder'   => __(''),
    ), WC()->session->get('installment_fee') ? '1' : '' );

    echo '</th><td>';
}

// jQuery - Ajax script
add_action( 'wp_footer', 'checkout_fee_script' );
function checkout_fee_script() {
    // Only on Checkout
    if( is_checkout() && ! is_wc_endpoint_url() ) :

    if( WC()->session->__isset('installment_fee') )
        WC()->session->__unset('installment_fee')
    ?>
    <script type="text/javascript">
    jQuery( function($){
        if (typeof wc_checkout_params === 'undefined')
            return false;

        $('form.checkout').on('change', 'input[name=installment_fee]', function(){
            var fee = $(this).prop('checked') === true ? '1' : '';

            $.ajax({
                type: 'POST',
                url: wc_checkout_params.ajax_url,
                data: {
                    'action': 'installment_fee',
                    'installment_fee': fee,
                },
                success: function (result) {
                    $('body').trigger('update_checkout');
                },
            });
        });
    });
    </script>
    <?php
    endif;
}

// Get Ajax request and saving to WC session
add_action( 'wp_ajax_installment_fee', 'get_installment_fee' );
add_action( 'wp_ajax_nopriv_installment_fee', 'get_installment_fee' );
function get_installment_fee() {
    if ( isset($_POST['installment_fee']) ) {
        WC()->session->set('installment_fee', ($_POST['installment_fee'] ? true : false) );
    }
    die();
}


// Add a custom calculated fee conditionally
add_action( 'woocommerce_cart_calculate_fees', 'set_installment_fee' );
function set_installment_fee( $cart ){
    if ( is_admin() && ! defined('DOING_AJAX') || ! is_checkout() )
        return;

    if ( did_action('woocommerce_cart_calculate_fees') >= 2 )
        return;

    if ( 1 == WC()->session->get('installment_fee') ) {
        $items_count = WC()->cart->get_cart_contents_count();
        $fee_label   = sprintf( __( "Support installation %s %s" ), '&times;', $items_count );
        $fee_amount  = 50000 * $items_count;
        WC()->cart->add_fee( $fee_label, $fee_amount );
    }
}

add_filter( 'woocommerce_form_field' , 'remove_optional_txt_from_installment_checkbox', 10, 4 );
function remove_optional_txt_from_installment_checkbox( $field, $key, $args, $value ) {
    // Only on checkout page for Order notes field
    if( 'installment_fee' === $key && is_checkout() ) {
        $optional = '&nbsp;<span class="optional">(' . esc_html__( 'optional', 'woocommerce' ) . ')</span>';
        $field = str_replace( $optional, '', $field );
    }
    return $field;
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works on Woocommerce version 3.6.5 with Storefront theme.

I have tried to adapt LoicTheAztec's code for this scenario:

Add a shipping insurance uprade checkbox to overseas orders only

(Just one checkbox per order, regardless of number of cart items)

It seems to be working but I am not convinced the coding is correct. I fear it might have a bug. Anyone can help with something better? Thank you

// START - Display Shipping Cover Upgrade Checkbox at Checkout

add_action( 'woocommerce_review_order_before_order_total', 'upgrade_shipping_cover_checkbox_field', 20 );

function upgrade_shipping_cover_checkbox_field(){
    $shipping_packages =  WC()->cart->get_shipping_packages();
    // Get the WC_Shipping_Zones instance object for the first package
    $shipping_zone = wc_get_shipping_zone( reset( $shipping_packages ) );
    $zone_id   = $shipping_zone->get_id(); // Get the zone ID
    if ($zone_id <> 1) {
        echo '<tr class="cover-upgrade-select"><th>';

        woocommerce_form_field( 'cover_upgrade_fee', array(
            'type'          => 'checkbox',
            'class'         => array('cover-upgrade-fee form-row-wide'),
            'label'         => __('&#43;&pound;2.50 : Upgrade Shipping Cover up to &pound;250'),
            'placeholder'   => __(''),
        ), WC()->session->get('cover_upgrade_fee') ? '1' : '' );

        echo '</th><td>';
    }
}

// jQuery - Ajax script

add_action( 'wp_footer', 'upgrade_shipping_cover_script' );

function upgrade_shipping_cover_script() {
    // Only on Checkout
    if( is_checkout() && ! is_wc_endpoint_url() ) :

    if( WC()->session->__isset('cover_upgrade_fee') )
        WC()->session->__unset('cover_upgrade_fee')
    ?>
    <script type="text/javascript">
    jQuery( function($){
        if (typeof wc_checkout_params === 'undefined')
            return false;

        $('form.checkout').on('change', 'input[name=cover_upgrade_fee]', function(){
            var fee = $(this).prop('checked') === true ? '1' : '';

            $.ajax({
                type: 'POST',
                url: wc_checkout_params.ajax_url,
                data: {
                    'action': 'cover_upgrade_fee',
                    'cover_upgrade_fee': fee,
                },
                success: function (result) {
                    $('body').trigger('update_checkout');
                },
            });
        });
    });
    </script>
    <?php
    endif;
}

// Get Ajax request and saving to WC session

add_action( 'wp_ajax_cover_upgrade_fee', 'get_cover_upgrade_fee' );

add_action( 'wp_ajax_nopriv_cover_upgrade_fee', 'get_cover_upgrade_fee' );

function get_cover_upgrade_fee() {
    if ( isset($_POST['cover_upgrade_fee']) ) {
        WC()->session->set('cover_upgrade_fee', ($_POST['cover_upgrade_fee'] ? true : false) );
    }
    die();
}

// Add a custom calculated fee conditionally

add_action( 'woocommerce_cart_calculate_fees', 'set_cover_upgrade_fee' );

function set_cover_upgrade_fee( $cart ){
    if ( is_admin() && ! defined('DOING_AJAX') || ! is_checkout() )
        return;

    if ( did_action('woocommerce_cart_calculate_fees') >= 2 )
        return;

    if ( 1 == WC()->session->get('cover_upgrade_fee') ) {
      //  $items_count = WC()->cart->get_cart_contents_count();
      //  $fee_label   = sprintf( __( "&pound;2.50 : Upgrade Shipping Cover to up to &pound;250 %s %s" ), '&times;', $items_count );
        $fee_label   = sprintf( __( "Shipping Cover Upgrade up to &pound;250" ) );
        $fee_amount  = 2.50;
        WC()->cart->add_fee( $fee_label, $fee_amount );
    }
}

add_filter( 'woocommerce_form_field' , 'remove_optional_txt_from_installment_checkbox', 10, 4 );

function remove_optional_txt_from_installment_checkbox( $field, $key, $args, $value ) {
    // Only on checkout page for Order notes field
    if( 'cover_upgrade_fee' === $key && is_checkout() ) {
        $optional = '&nbsp;<span class="optional">(' . esc_html__( 'optional', 'woocommerce' ) . ')</span>';
        $field = str_replace( $optional, '', $field );
    }
    return $field;
}

// END - Display Shipping Cover Upgrade Checkbox at Checkout

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM