小怪兽爱吃肉
已更新-处理多个不允许的目的地...首先,为了进行测试,我在这里提供了一个挂钩函数,该函数显示了一个自定义结帐选择字段,其中包含很少的选项:// Just for testingadd_action( 'woocommerce_after_checkout_billing_form', 'custom_select_field_after_checkout_billing_form', 10, 1 );function custom_select_field_after_checkout_billing_form ( $checkout ) { woocommerce_form_field( 'wc_billing_field_7378', array( 'type' => 'select', 'label' => __( "Destinations (custom select field)"), 'class' => array( 'form-row-wide' ), 'options' => array( '' => __("Choose a destination"), 'naeem' => __("Naeem"), 'saad-al-abdullah' => __("Saad Al Abdullah"), 'other-one' => __("Other one"), 'last-one' => __("Last one"), ), 'required' => true, ), $checkout->get_value( 'wc_billing_field_7378' ) );}参见下面的显示:现在,要使此功能正常运行,需要jQuery和Ajax,以便能够启用或禁用“鳕鱼”付款,具体取决于从此自定义结帐选择字段中选择的选项值。有了这个代码,当“纳伊姆”或者选择“另一个人”,它会隐藏“货到付款”(COD)付款方式......如果选择了其他选项,“货到付款”会再次出现。这是这段代码:// Jquery script that send the Ajax requestadd_action( 'wp_footer', 'custom_checkout_js_script' );function custom_checkout_js_script() { // Only on checkout if( is_checkout() && ! is_wc_endpoint_url() ) : ?> <script type="text/javascript"> jQuery(function($){ if (typeof wc_checkout_params === 'undefined') return false; var field = 'select[name="wc_billing_field_7378"]'; $( 'form.checkout' ).on('change blur', field, function() { $.ajax({ type: 'POST', url: wc_checkout_params.ajax_url, data: { 'action': 'checkout_chosen_destination', 'chosen_destination': $(this).val(), }, success: function (result) { $(document.body).trigger('update_checkout'); console.log(result); // For testing only }, }); }); }); </script> <?php endif;}// The Wordpress Ajax PHP receiveradd_action( 'wp_ajax_checkout_chosen_destination', 'get_ajax_checkout_chosen_destination' );add_action( 'wp_ajax_nopriv_checkout_chosen_destination', 'get_ajax_checkout_chosen_destination' );function get_ajax_checkout_chosen_destination() { // Checking that the posted email is valid if ( isset($_POST['chosen_destination']) ) { // Set the value in a custom Woocommerce session identifier WC()->session->set('chosen_destination', esc_attr($_POST['chosen_destination']) ); // Return the session value to jQuery echo json_encode(WC()->session->get('chosen_destination')); // For testing only } die(); // always use die at the end}// Show/Hide payment gatewaysadd_filter('woocommerce_available_payment_gateways', 'show_hide_cod_payment_method', 10, 1 );function show_hide_cod_payment_method( $available_gateways ) { // Not in backend (admin) if( is_admin() ) return $available_gateways; // HERE below set the not allowed destinations in the array $not_allowed_destinations = array('naeem', 'other-one'); if ( in_array( WC()->session->get('chosen_destination'), $not_allowed_destinations ) ) { unset($available_gateways['cod']); } return $available_gateways;}代码进入您的活动子主题(或活动主题)的function.php文件中。经过测试和工作。