How to Auto-Populate the Billing Email Field in WooCommerce Checkout Page with the woocommerce_checkout_get_value Filter

woocommerce

The woocommerce_checkout_get_value filter is a filter provided by the WooCommerce plugin for WordPress. This filter allows you to modify the value of a checkout field before it is displayed to the user during the checkout process.

The woocommerce_checkout_get_value filter accepts two parameters:

  1. $value (mixed): The current value of the checkout field.
  2. $input (string): The name of the checkout field.
/**
 * Filter to alter the checkout field values.
 * @param $value
 * @param $input
 * @return mixed|string
 */
function filter_woocommerce_checkout_get_value( $value, $input ) {
    // if the field is the billing email field
    if ( 'billing_email' === $input ) {
        $current_user = wp_get_current_user();
	// if the current user is logged in, force the email to be the current user's email
	if ( $current_user->ID ) {
	    // get the user email
	    $value = $current_user->user_email;
	}
    }

    return $value;
}
add_filter( 'woocommerce_checkout_get_value', 'filter_woocommerce_checkout_get_value', 10, 2 );

In the code snippet above, we check if the current checkout field is the “billing_email” field. If it is, the function gets the current logged-in user’s email address and sets it as the value of the “billing_email” field. For guest users, it follows the default process of allowing them to enter the billing email field.

This is done to ensure that the user’s email address is correctly associated with the order. If you would like to hide the billing field and/or make it read-only, you can check this post where I explain how to do so with the woocommerce_checkout_fields filter.


Posted

in

,

by

%d bloggers like this: