Skip to content

Commit

Permalink
feat(modal-checkout): allow anonymous purchase for registered email (#…
Browse files Browse the repository at this point in the history
…1615)

Co-authored-by: leogermani <[email protected]>
  • Loading branch information
miguelpeixe and leogermani authored Dec 18, 2023
1 parent 115e9fb commit a0040b4
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions includes/class-modal-checkout.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@ public static function init() {
add_filter( 'woocommerce_order_button_text', [ __CLASS__, 'order_button_text' ] );
add_filter( 'option_woocommerce_subscriptions_order_button_text', [ __CLASS__, 'order_button_text' ] );

/** Custom handling for registered users. */
add_filter( 'woocommerce_checkout_customer_id', [ __CLASS__, 'associate_existing_user' ] );
add_filter( 'woocommerce_checkout_posted_data', [ __CLASS__, 'skip_account_creation' ], 11 );

// Remove some stuff from the modal checkout page. It's displayed in an iframe, so it should not be treated as a separate page.
add_action( 'wp_enqueue_scripts', [ __CLASS__, 'dequeue_scripts' ], 11 );
add_filter( 'newspack_reader_activation_should_render_auth', [ __CLASS__, 'is_not_modal_checkout_filter' ] );
Expand Down Expand Up @@ -973,6 +977,50 @@ public static function order_button_text( $text ) {
return $text;
}

/**
* If a reader tries to make a purchase with an email address that
* has been previously registered, automatically associate the transaction
* with the user.
*
* @param int $customer_id Current customer ID.
*
* @return int Modified $customer_id
*/
public static function associate_existing_user( $customer_id ) {
if ( ! self::is_modal_checkout() ) {
return $customer_id;
}
$billing_email = filter_input( INPUT_POST, 'billing_email', FILTER_SANITIZE_EMAIL );
if ( $billing_email ) {
$customer = \get_user_by( 'email', $billing_email );
if ( $customer ) {
$customer_id = $customer->ID;
}
}
return $customer_id;
}

/**
* Don't force account registration/login on Woo purchases for existing users.
*
* @param array $data Array of Woo checkout data.
*
* @return array Modified $data.
*/
public static function skip_account_creation( $data ) {
if ( ! self::is_modal_checkout() ) {
return $data;
}
$email = $data['billing_email'];
$customer = \get_user_by( 'email', $email );
if ( $customer ) {
$data['createaccount'] = 0;
\add_filter( 'woocommerce_checkout_registration_required', '__return_false', 9999 );
}

return $data;
}

/**
* Filter the a value dependent on the page not being modal checkout.
*
Expand Down

0 comments on commit a0040b4

Please sign in to comment.