Hiding order fields depending on the selected delivery method WooCommerce

Posted

Step one. Adding the shape of the fields to the snippet


WooCommerce has such a functionality of fragments, you can add the desired html to them and display in the right place. So, add the snippet

The code has been changed. The previous snippet will work, but if the store uses a personal account, then there will be problems. Since this form is connected in the checkout / form-billing.php file, it is more correct to use the following code

/**
 * Добавляем часть формы к фрагменту
 *
 * @sourcecode    https://wpruse.ru/woocommerce/hiding-fields-on-chosen-delivery/
 *
 * @param $fragments
 *
 * @return mixed
 *
 * @sourcecode    https://wpruse.ru/woocommerce/hiding-fields-on-chosen-delivery/
 * @author        Artem Abramovich
 * @testedwith    WC 5.5
 */
function awoohc_add_update_form_billing( $fragments ) {

	$checkout = WC()->checkout();

	parse_str( $_POST['post_data'], $fields_values );

	ob_start();

	echo '<div class="woocommerce-billing-fields__field-wrapper">';

	$fields = $checkout->get_checkout_fields( 'billing' );

	foreach ( $fields as $key => $field ) {
		$value = $checkout->get_value( $key );

		if ( isset( $field['country_field'], $fields[ $field['country_field'] ] ) ) {
			$field['country'] = $checkout->get_value( $field['country_field'] );
		}

		if ( ! $value && ! empty( $fields_values[ $key ] ) ) {
			$value = $fields_values[ $key ];
		}

		woocommerce_form_field( $key, $field, $value );
	}

	echo '</div>';

	$fragments['.woocommerce-billing-fields__field-wrapper'] = ob_get_clean();

	return $fragments;
}

add_filter( 'woocommerce_update_order_review_fragments', 'awoohc_add_update_form_billing', 99 );

Step two. Removing unnecessary fields

Shipping methods are assumed to be configured. For example, two methods have been created. Now you need to specify the desired shipping method identifier. The easiest way is to look in the source code

Selected lines are identifiers. Now it is enough to make a check and if we get the desired delivery method, delete the extra fields

/**
 * Скрываем поля для бесплатного способа доставки
 *
 * @param $fields
 *
 * @return mixed
 *
 * @sourcecode    https://wpruse.ru/woocommerce/hiding-fields-on-chosen-delivery/
 * @author        Artem Abramovich
 * @testedwith    WC 5.5
 */
function awoohc_override_checkout_fields( $fields ) {

	// получаем выбранные методы доставки.
	$chosen_methods = WC()->session->get( 'chosen_shipping_methods' );

	// проверяем текущий метод и убираем не ненужные поля.
	if ( false !== strpos( $chosen_methods[0], 'free_shipping' ) ) {
		unset(
			$fields['billing']['billing_company'],
			$fields['billing']['billing_address_1'],
			$fields['billing']['billing_address_2'],
			$fields['billing']['billing_city'],
			$fields['billing']['billing_postcode'],
			$fields['billing']['billing_state'],
			$fields['billing']['billing_phone'],
			$fields['billing']['billing_email']
		);
	}

	return $fields;
}

add_filter( 'woocommerce_checkout_fields', 'awoohc_override_checkout_fields' );

Step three. Refreshing the page

Everything works except for refreshing the page. Let’s add some ajax magic, since all the processing of fields on the Checkout page is done via ajax.

/**
 * Прелоад при переключении доставки
 *
 * @sourcecode    https://wpruse.ru/woocommerce/hiding-fields-on-chosen-delivery/
 * @author        Artem Abramovich
 * @testedwith    WC 5.5
 */
function awoohc_add_script_update_shipping_method() {

	if ( is_checkout() ) {
		?>
		<!--Скроем поле Страна. Если успользуется поле Страна, то следцет убрать скрытие-->
		<style>
			#billing_country_field {
				display: none !important;
			}
		</style>

		<!--Выполняем обновление полей при переключении доставки-->
		<script>
			  jQuery( document ).ready( function( $ ) {
				  $( document.body ).on( 'updated_checkout updated_shipping_method', function( event, xhr, data ) {
					  $( 'input[name^="shipping_method"]' ).on( 'change', function() {
						  $( '.woocommerce-billing-fields__field-wrapper' ).block( {
							  message: null,
							  overlayCSS: {
								  background: '#fff',
								  'z-index': 1000000,
								  opacity: 0.3
							  }
						  } );
					  } );
				  } );
			  } );
		</script>
		<?php
	}
}

add_action( 'wp_footer', 'awoohc_add_script_update_shipping_method' );

The code is connected to the wp_footer hook, if desired, it can be placed in a separate file. The code was tested against the standard StoreFront theme. Everything should work correctly.

And the update of the fields is also done not after the update of the delivery methods, but in parallel with this update