根据购物车合计(小计+运费)计算费用,而不将其添加到WooCommerce中的订单总价值

2022-09-03 00:00:00 php wordpress woocommerce checkout fee

根据Add a checkout checkbox field that enable a percentage fee in Woocommerce答案代码,我在结账页上创建了一个复选框。

勾选后,将收取15%的货运代理费。

// Add a custom checkbox fields before order notes
add_action( 'woocommerce_before_order_notes', 'add_custom_checkout_checkbox', 20 );
function add_custom_checkout_checkbox(){

    // Add a custom checkbox field
    woocommerce_form_field( 'forwarding_fee', array(
        'type'  => 'checkbox',
        'label' => __('15% forwarding fee'),
        'class' => array( 'form-row-wide' ),
    ), '' );
}


// 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('enable_fee') )
        WC()->session->__unset('enable_fee')
    ?>
    <script type="text/javascript">
    jQuery( function($){
        if (typeof wc_checkout_params === 'undefined') 
            return false;

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

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

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

// Add a custom dynamic 15% fee
add_action( 'woocommerce_cart_calculate_fees', 'custom_percetage_fee', 20, 1 );
function custom_percetage_fee( $cart ) {
    // Only on checkout
    if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) || ! is_checkout() )
        return;

    $percent = 15;

    if( WC()->session->get('enable_fee') )
        $cart->add_fee( __( 'Forwarding fee', 'woocommerce')." ($percent%)", ($cart->get_subtotal() * $percent / 100) );
}

目前,此费用是从小计中计算出来的,然后加到订单总值中。

我需要一个解决方案,其中这笔费用是根据小计+运费的总和计算的,并且不会添加到订单总价值中。

我将把";费用";重命名为";存款。


请查看屏幕截图:


解决方案

因为您不想将其添加到总计中,所以您可以向woocommerce-checkout-review-order-table添加自定义表行而不是购物车费用。所以我的回答不是基于WooCommerce费用,并且与它完全分开。

然后,自定义表行将根据是否选中该复选框来显示/隐藏百分比。

通过一行注释进行的解释,已添加到我的答案中。

因此您得到:

// Add checkbox field
function action_woocommerce_before_order_notes( $checkout ) {
    // Add field
    woocommerce_form_field( 'my_id', array(
        'type'          => 'checkbox',
        'class'         => array( 'form-row-wide' ),
        'label'         => __( '15% and some other text', 'woocommerce' ),
        'required'      => false,  
    ), $checkout->get_value( 'my_id' ));
}
add_action( 'woocommerce_before_order_notes', 'action_woocommerce_before_order_notes', 10, 1 );

// Save checkbox value
function action_woocommerce_checkout_create_order( $order, $data ) {
    // Set the correct value
    $checkbox_value = isset( $_POST['my_id'] ) ? 'yes' : 'no';
    
    // Update meta data
    $order->update_meta_data( '_my_checkbox_value', $checkbox_value );
}
add_action( 'woocommerce_checkout_create_order', 'action_woocommerce_checkout_create_order', 10, 2 );

// Add table row on the checkout page
function action_woocommerce_before_order_total() {
    // Initialize
    $percent = 15;
    
    // Get subtotal & shipping total
    $subtotal       = WC()->cart->subtotal;
    $shipping_total = WC()->cart->get_shipping_total();
    
    // Total
    $total = $subtotal + $shipping_total;
    
    // Result
    $result = ( $total / 100 ) * $percent;
    
    // The Output
    echo '<tr class="my-class">
        <th>' . __( 'My text', 'woocommerce' ) . '</th>
        <td data-title="My text">' . wc_price( $result ) . '</td>
    </tr>';
}
add_action( 'woocommerce_review_order_before_order_total', 'action_woocommerce_before_order_total', 10, 0 );
    
// Show/hide table row on the checkout page with jQuery
function action_wp_footer() {
    // Only on checkout
    if ( is_checkout() && ! is_wc_endpoint_url() ) :
    ?>
    <script type="text/javascript">
    jQuery( function($){
        // Selector
        var my_input = 'input[name=my_id]';
        var my_class = '.my-class';
        
        // Show or hide
        function show_or_hide() {
            if ( $( my_input ).is(':checked') ) {
                return $( my_class ).show();
            } else {
                return $( my_class ).hide();               
            }           
        }
        
        // Default
        $( document ).ajaxComplete(function() {
            show_or_hide();
        });
        
        // On change
        $( 'form.checkout' ).change(function() {
            show_or_hide();
        });
    });
    </script>
    <?php
    endif;
}
add_action( 'wp_footer', 'action_wp_footer', 10, 0 );

// If desired, add new table row to emails, order received (thank you page) & my account -> view order
function filter_woocommerce_get_order_item_totals( $total_rows, $order, $tax_display ) {    
    // Get checkbox value
    $checkbox_value = $order->get_meta( '_my_checkbox_value' );
    
    // NOT equal to yes, return
    if ( $checkbox_value != 'yes' ) return $total_rows;
    
    // Initialize
    $percent = 15;
    
    // Get subtotal & shipping total
    $subtotal       = $order->get_subtotal();
    $shipping_total = $order->get_shipping_total();
    
    // Total
    $total = $subtotal + $shipping_total;
    
    // Result
    $result = ( $total / 100 ) * $percent;
    
    // Save the value to be reordered
    $order_total = $total_rows['order_total'];
    
    // Remove item to be reordered
    unset( $total_rows['order_total'] );
    
    // Add new row
    $total_rows['my_text'] = array(
        'label' =>  __( 'My text:', 'woocommerce' ),
        'value' => wc_price( $result ),
    );
    
    // Reinsert removed in the right order
    $total_rows['order_total'] = $order_total;

    return $total_rows;
}
add_filter( 'woocommerce_get_order_item_totals', 'filter_woocommerce_get_order_item_totals', 10, 3 );

相关文章