php - Woocommerce 3 中的自定义结账字段和运输方式 ajax 交互

标签 php jquery ajax wordpress woocommerce

这个问题很快就会让我去邮寄......

在 Woocommerce Checkout 中,我需要在地址中添加自定义字段。 这个额外的字段用于函数calculate_shipping($package = array())

现在显然 woocommerce/wordpress 不允许访问此函数调用中的这些自定义字段..不明白为什么,但我们继续前进..

那么解决方案就是 jQuery,对吧? ..没那么快.. 每个示例都不会将值返回到 woocommerce 环境.. 没有一个 ..

接下来是我迄今为止在这个兔子洞中获取单个字段值的代码......

//We first add the field to the checkout form
add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields');

function custom_override_checkout_fields( $fields ) {
     $fields['billing']['billing_area'] = array(
         'label'     => __('Area', 'woocommerce'),
         'placeholder'   => _x('Area', 'placeholder', 'woocommerce'),
         'required'  => true,
         'class'     => array('form-row-wide' ),
         'clear'     => true,
         'priority' => 61
     );

     return $fields;
}

// we load the scripts and the ajax callback functions

add_action( 'wp_enqueue_scripts', 'so18550905_enqueue_scripts' );
add_action( 'wp_ajax_myaction', 'so18550905_wp_ajax_function' );
add_action( 'wp_ajax_nopriv_myaction' , 'so18550905_wp_ajax_function' );

function so18550905_enqueue_scripts(){
    wp_register_script( 'ajaxHandle', plugins_url() . '/miguel-shipping/test.js', array('jquery'), '1.0', true );
    wp_enqueue_script( 'ajaxHandle' );
    wp_localize_script( 'ajaxHandle', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin_ajax.php' ) ) );
}

function so18550905_wp_ajax_function(){
  //this function should be called but it is not for some reason..
  $testingitouthere=$_POST['my_billing_area'] ;
  file_put_contents('blablablabla.txt', print_r($testingitouthere,true));
  wp_die(); 
}

JS 代码:

jQuery(document).ready( function($){

    $('#billing_area').change(function () {
        var billing_area = $('#billing_area').val();
        console.log(billing_area);

    $.ajax({
        url: ajax_object.ajaxurl, // this is the object instantiated in wp_localize_script function
        type: 'POST',
        data:{
            action: 'myaction', 
            my_billing_area: billing_area 
        },
        success: function( data ){
        //Do something with the result from server
        console.log( data );
        }
    });
    return false;
});

});

问题是php中调用的函数

so18550905_wp_ajax_function()

只是永远不会被触发..我正在该函数中写入文件(在有人询问之前)仅用于测试..一旦我到达这一点,我将从那里继续编码... Jquery 也记录到控制台..

最佳答案

尝试以下重新访问的代码,该代码基于您提供的代码,该代码将通过 Ajax 在自定义 WC_Session 中添加“计费区域”字段的值。

Then you will be able to get the live value using: $value = WC()->session->get('billing_area'); in a custom function hooked in woocommerce_shipping_packages filter hook located in WC_Shipping method calculate_shipping() as you asked.

代码:

// Add a custom billing field
add_filter( 'woocommerce_billing_fields', 'add_custom_billing_field', 20, 1 );
function add_custom_billing_field($billing_fields) {

    $billing_fields['billing_area'] = array(
        'label'     => __('Area', 'woocommerce'),
        'placeholder'   => _x('Fill in your area', 'placeholder', 'woocommerce'),
        'required'  => true,
        'class'     => array('form-row-wide' ),
        'clear'     => true,
        'priority' => 65
    );
    return $billing_fields;
}

// The Wordpress Ajax PHP receiver
add_action( 'wp_ajax_billing_area', 'get_ajax_billing_area' );
add_action( 'wp_ajax_nopriv_billing_area', 'get_ajax_billing_area' );
function get_ajax_billing_area() {
    if ( isset($_POST['billing_area']) ){
        WC()->session->set('billing_area', esc_attr($_POST['billing_area']));
        echo $_POST['billing_area'];
    }
    die();
}

// Refreshing session shipping methods data (Mandatory)
add_action( 'woocommerce_checkout_update_order_review', 'refresh_shipping_methods', 10, 1 );
function refresh_shipping_methods( $post_data ){
    $bool = true;
    if ( WC()->session->get('billing_area' ) != '' ) $bool = false;

    // Mandatory to make it work with shipping methods
    foreach ( WC()->cart->get_shipping_packages() as $package_key => $package ){
        WC()->session->set( 'shipping_for_package_' . $package_key, $bool );
    }
    WC()->cart->calculate_shipping();
}

// The jQuery Ajax request
add_action( 'wp_footer', 'checkout_billing_area_script' );
function checkout_billing_area_script() {
    // Only checkout page
    if( is_checkout() && ! is_wc_endpoint_url() ):

    // Remove "billing_area" custom WC session on load
    if( WC()->session->get('billing_area') ){
        WC()->session->__unset('billing_area');
    }
    // jQuery Ajax code below
    ?>
    <script type="text/javascript">
    jQuery( function($){
        if (typeof wc_checkout_params === 'undefined')
            return false;

        var a = '#billing_area', f = 'form.checkout';

        // Ajax function
        function checkBArea( value ){
             $.ajax({
                type: 'POST',
                url: wc_checkout_params.ajax_url,
                data: {
                    'action': 'billing_area',
                    'billing_area': value,
                },
                success: function (result) {
                    $('body').trigger('update_checkout');
                    console.log(result); // For testing (to be removed)
                }
            });
        }

        // On start
        if( $(a).val() != '' )
            checkBArea($(a).val());

        // On change event
        $(f).on('change', a, function() {
            checkBArea($(this).val());
        });
    });
    </script>
    <?php
    endif;
}

代码位于事件子主题(事件主题)的 function.php 文件中。经过测试并有效。

<小时/>

类似或相关主题:

关于php - Woocommerce 3 中的自定义结账字段和运输方式 ajax 交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52668693/

相关文章:

javascript - 使用 jQuery mobile 将 DIV 动态添加到 BODY

javascript - Rails 无需离开页面即可更新模型

ajax - 事件不适用于动态创建的元素

php - 下载文件已损坏 - header

javascript - 如何销毁/重新加载 html 5 中的 Canvas ?

javascript - 在 PayPal 按钮重定向之前完成 AJAX 调用

javascript - jQuery 自相矛盾

jquery - 使用 Ajax 和 ASP.NET 将图像上传并保存到服务器,无需刷新

php - 在 PHP 扩展中从线程使用 emalloc 时出现段错误

php - 如果 MYSQL [BLOB] 为 NULL,我该如何更新