WooCommerce – How to maintain the state of “Ship to a different address” Checkbox

On WooCommerce checkout page if you tick the “Ship to a different address” checkbox, then redirect to some other page maybe to add some more products to the cart, and then come back again to the checkout page, you would notice that “Ship to a different address” checkbox resets to its default state.

You can use the below code snippet to make WooCommerce remember the state of that checkbox.

<?php

/**
 * Maintain Ship to specific address session.
 *
 * @param string $posted_data
 */
function maintain_ship_to_different_address_session( $posted_data ) {
	$data = array();

	parse_str( $posted_data, $data );

	if ( isset( $data['ship_to_different_address'] ) && $data['ship_to_different_address'] ) {
		WC()->session->set( 'ship_to_different_address', '1' );
	} else {
		WC()->session->set( 'ship_to_different_address', '0' );
	}
}
add_action('woocommerce_checkout_update_order_review', 'maintain_ship_to_different_address_session');

/**
 * Override ship to specific checkbox
 *
 * @param bool $checked
 *
 * @return bool
 */
function override_ship_to_specific_checkbox_value( $checked ) {
	$ship_to_different_address = WC()->session->get( 'ship_to_different_address' );
	return '1' == $ship_to_different_address ? true : $checked;
}
add_filter( 'woocommerce_ship_to_different_address_checked', 'override_ship_to_specific_checkbox_value', 10, 1 );

Just add this code snippet to the functions.php of your child theme or use the Code snippet plugin.

Moreover, WordPress Hooks and Filters API is also something I can’t express enough gratitude for. You can do so many amazing things using actions while maintaining backward compatibility.

  1. Awesome Pramod its a relevant code snippet and insight . I am Sumant Bhattacharya and also a WordPress Consultant and SEO. Hope you recall me as Trainer in Global.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Up Next:

WooCommerce - How to offer a free product with the purchase of certain products

WooCommerce - How to offer a free product with the purchase of certain products