@@ -22,6 +22,13 @@ class Checkout_Mutation {
2222 */
2323 private static $ fields ;
2424
25+ /**
26+ * Caches customer object. @see get_value.
27+ *
28+ * @var WC_Customer
29+ */
30+ private $ logged_in_customer = null ;
31+
2532 /**
2633 * Is registration required to checkout?
2734 *
@@ -78,11 +85,14 @@ public static function prepare_checkout_args( $input, $context, $info ) {
7885 }
7986
8087 foreach ( $ fieldset as $ field => $ input_key ) {
88+ $ key = "{$ fieldset_key }_ {$ field }" ;
8189 $ value = ! empty ( $ input [ $ fieldset_key ][ $ input_key ] )
8290 ? $ input [ $ fieldset_key ][ $ input_key ]
8391 : null ;
8492 if ( $ value ) {
85- $ data [ "{$ fieldset_key }_ {$ field }" ] = $ value ;
93+ $ data [ $ key ] = $ value ;
94+ } elseif ( 'billing_country ' === $ key || 'shipping_country ' === $ key ) {
95+ $ data [ $ key ] = self ::get_value ( $ key );
8696 }
8797 }
8898 }
@@ -516,4 +526,46 @@ public static function process_checkout( $data, $context, $info, &$results = nul
516526
517527 return $ order_id ;
518528 }
529+
530+ /**
531+ * Gets the value either from 3rd party logic or the customer object. Sets the default values in checkout fields.
532+ *
533+ * @param string $input Name of the input we want to grab data for. e.g. billing_country.
534+ * @return string The default value.
535+ */
536+ public static function get_value ( $ input ) {
537+ // Allow 3rd parties to short circuit the logic and return their own default value.
538+ $ value = apply_filters ( 'woocommerce_checkout_get_value ' , null , $ input );
539+ if ( ! is_null ( $ value ) ) {
540+ return $ value ;
541+ }
542+
543+ /**
544+ * For logged in customers, pull data from their account rather than the session which may contain incomplete data.
545+ * Another reason is that WC sets shipping address to the billing address on the checkout updates unless the
546+ * "shipToDifferentAddress" is set.
547+ */
548+ $ customer_object = false ;
549+ if ( is_user_logged_in () ) {
550+ // Load customer object, but keep it cached to avoid reloading it multiple times.
551+ if ( is_null ( self ::$ logged_in_customer ) ) {
552+ self ::$ logged_in_customer = new WC_Customer ( get_current_user_id (), true );
553+ }
554+ $ customer_object = new WC_Customer ( get_current_user_id (), true );
555+ }
556+
557+ if ( ! $ customer_object ) {
558+ $ customer_object = WC ()->customer ;
559+ }
560+
561+ if ( is_callable ( array ( $ customer_object , "get_ $ input " ) ) ) {
562+ $ value = $ customer_object ->{"get_ $ input " }();
563+ } elseif ( $ customer_object ->meta_exists ( $ input ) ) {
564+ $ value = $ customer_object ->get_meta ( $ input , true );
565+ }
566+ if ( '' === $ value ) {
567+ $ value = null ;
568+ }
569+ return apply_filters ( 'default_checkout_ ' . $ input , $ value , $ input );
570+ }
519571}
0 commit comments