在签出页面上更改运送方法时,触发了哪种方法或操作挂钩


Which method or action hook is fired when changing shipping method on checkout page?

当用户选择"本地取货"以外的运输方式时,我需要将地址字段更改为"必需"。

我设法使用过滤器使其在默认情况下是可选的(默认情况下选择本地取货),如下所示:

add_filter( 'woocommerce_checkout_fields', 'disable_required_address_shipping' );
function disable_required_address_shipping($fields ) {
    if ( check_if_local_pickup() ) {
        $fields['billing']['billing_address_1']['required'] = false;
        $fields['billing']['billing_address_2']['required'] = false;
        $fields['billing']['billing_city']['required'] = false;
    }
    return $fields;
}
function check_if_local_pickup() {
    $chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
    $chosen_shipping = $chosen_methods[0]; 
    if ($chosen_shipping == 'local_pickup') { 
        return true;
    }
}

但我需要使用一个操作来动态地更改它。

我试图在这里寻找解决方案,但找不到。

更改运输方式时是否有任何触发的操作
有什么想法吗?

要在运输方法更改时触发操作,可以使用do_action( 'woocommerce_shipping_method_chosen', $chosen_method );:

do_action( 'woocommerce_shipping_method_chosen', 'check_if_local_pickup', 10, 1 );
function check_if_local_pickup( $chosen_method ) {
    $chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
    $chosen_shipping = $chosen_methods[0]; 
    if ($chosen_shipping == 'local_pickup') { 
        return true;
    }
}

参考文献:
woommerce_shipping_method_chosen(hook.io)
源代码:类WC_Shipping(第311行)