Display a checkbox that add a fee in Woocommerce checkout page

前端 未结 1 1362
盖世英雄少女心
盖世英雄少女心 2021-01-15 13:50

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 fe

1条回答
  •  花落未央
    2021-01-15 14:28

    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 '';
    
        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 '';
    }
    
    // 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')
        ?>
        
        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" ), '×', $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 = ' (' . esc_html__( 'optional', 'woocommerce' ) . ')';
            $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.

    0 讨论(0)
提交回复
热议问题