基于Woocommerce中的自定义单选按钮的动态运费 [英] Dynamic shipping fee based on custom radio buttons in Woocommerce

查看:132
本文介绍了基于Woocommerce中的自定义单选按钮的动态运费的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Woocommerce中,我在结帐页面上添加了两个自定义单选按钮,在单击时,我调用了ajax函数来添加送货费.

In Woocommerce, I have added two custom radio buttons on the checkout page and on click, I called an ajax function to add a delivery fee.

这是我的代码:

$(document).on('change','#shipping_method_0_local_pickup5',function(e) {              
            $('.woocommerce-shipping-fields').css({
                'display': 'none'
            });

                        $("#deli").css("display","block"); 
                        var selected = $("input[type='radio'][name='post-del']:checked");
                        var selectedVal = selected.val();               
                        var pickurl= "<?php echo admin_url('admin-ajax.php');?>?action=delivery";
                        $.ajax({   
                            url: pickurl,
                            type: "POST",
                            data:{
                                input:selectedVal,                       
                            },            
                            success: function(responseText) 
                            { 
                                jQuery(".order-total .woocommerce-Price-amount").html(responseText);
                                //$(".discount_code").css("display","block"); 
                            }
                        }); 

        });

当单选按钮单击时,我要在总数上增加$ 2.

add_action( 'wp_ajax_delivery', 'delivery' );
add_action( 'wp_ajax_nopriv_delivery', 'delivery' );

function delivery()
{      
    //My code  
    do_action( 'woocommerce_cart_calculate_fees', 'prefix_add_discount_line' ); // not working
    exit;
}

注意:这是更新代码的钩子

add_action( 'woocommerce_cart_calculate_fees', 'prefix_add_discount_line' );
function prefix_add_discount_line( $cart ) {

    $discount = $cart->subtotal + 2;

    $cart->add_fee( __( 'Delivery', 'yourtext-domain' ) , +$discount );

}

推荐答案

您应该在问题中提供所有必要的相关代码.请记住,寻求调试帮助的问题(为什么此代码为什么不起作用?")必须包含所需的行为,特定问题或错误,以及在问题本身中重现该问题所需的最短代码 strong>".

You should give all necessary related code in your question. Remember that "Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself".

因此,在下面的代码中,您将找到带有其他自定义单选按钮的完整的工作解决方案,该解决方案将根据所选的单选按钮和本地取件"运输方式动态增加送货费.

So, in the code below, you will find a complete working solution, with additional custom radio buttons, that will add dynamically a delivery fee depending on the selected radio button and for "local pickup" shipping method.

代码(您将需要在其中定义目标本地拾取"方法ID):

// Enabling delivery options for a specific defined shipping method
function targeted_shipping_method(){
    // HERE below define the shipping method Id that enable the custom delivery options
    return 'local_pickup:5';
}

// Customizing Woocommerce checkout radio form field
add_action( 'woocommerce_form_field_radio', 'custom_form_field_radio', 20, 4 );
function custom_form_field_radio( $field, $key, $args, $value ) {
    if ( ! empty( $args['options'] ) && is_checkout() ) {
        $field = str_replace( '</label><input ', '</label><br><input ', $field );
        $field = str_replace( '<label ', '<label style="display:inline;margin-left:8px;" ', $field );
    }
    return $field;
}

// Add a custom radio fields for packaging selection
add_action( 'woocommerce_review_order_after_shipping', 'checkout_shipping_form_delivery_addition', 20 );
function checkout_shipping_form_delivery_addition(){
    $domain = 'wocommerce';

    if (  WC()->session->get( 'chosen_shipping_methods' )[0] == targeted_shipping_method() ) :

        echo '<tr class="delivery-radio"><th>' . __('Delivery options', $domain) . '</th><td>';

        $chosen = WC()->session->get('chosen_delivery');
        $chosen = empty($chosen) ? WC()->checkout->get_value('delivery') : $chosen;
        $chosen = empty($chosen) ? 'regular' : $chosen;

        // Add a custom checkbox field
        woocommerce_form_field( 'radio_delivery', array(
            'type' => 'radio',
            'class' => array( 'form-row-wide' ),
            'options' => array(
                'regular' => __('Regular', $domain),
                'premium' => __('Premium +'.wc_price(2.00), $domain),
            ),
            'default' => $chosen,
        ), $chosen );

        echo '</td></tr>';

    endif;
}

// jQuery - Ajax script
add_action( 'wp_footer', 'checkout_delivery_script' );
function checkout_delivery_script() {
    // Only checkout page
    if ( ! is_checkout() ) return;
    ?>
    <script type="text/javascript">
    jQuery( function($){
        if (typeof wc_checkout_params === 'undefined')
            return false;

        $('form.checkout').on('change', 'input[name=radio_delivery]', function(e){
            e.preventDefault();
            var d = $(this).val();
            $.ajax({
                type: 'POST',
                url: wc_checkout_params.ajax_url,
                data: {
                    'action': 'delivery',
                    'delivery': d,
                },
                success: function (result) {
                    $('body').trigger('update_checkout');
                    console.log(result); // just for testing | TO BE REMOVED
                },
                error: function(error){
                    console.log(error); // just for testing | TO BE REMOVED
                }
            });
        });
    });
    </script>
    <?php

}

// Get Ajax request and saving to WC session
add_action( 'wp_ajax_delivery', 'wc_get_delivery_ajax_data' );
add_action( 'wp_ajax_nopriv_delivery', 'wc_get_delivery_ajax_data' );
function wc_get_delivery_ajax_data() {
    if ( isset($_POST['delivery']) ){
        WC()->session->set('chosen_delivery', sanitize_key( $_POST['delivery'] ) );
        echo json_encode( $delivery ); // Return the value to jQuery
    }
    die();
}

// Add a custom dynamic delivery fee
add_action( 'woocommerce_cart_calculate_fees', 'add_packaging_fee', 20, 1 );
function add_packaging_fee( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Only for targeted shipping method
    if (  WC()->session->get( 'chosen_shipping_methods' )[0] != targeted_shipping_method() )
        return;

    if( WC()->session->get( 'chosen_delivery' ) == 'premium' )
        $cart->add_fee( __( 'Delivery fee', 'woocommerce' ), 2.00 );
}

代码进入您的活动子主题(或活动主题)的function.php文件中.经过测试,可以正常工作.

Code goes in function.php file of your active child theme (or active theme). Tested and works.

这篇关于基于Woocommerce中的自定义单选按钮的动态运费的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆