If you do a lot of manual work such as creating WordPress users for a B2B WooCommerce site (because they can only shop if they have an account, and you’ve disabled registration on the frontend), you may want to populate some Billing and Shipping fields so that you can save some time.
For example, imagine if all customers are based in Florida, USA; you could automatically populate their billing country, billing state, shipping country and shipping state!
So, let’s see how to approach this. Enjoy!
PHP Snippet: Assign Billing/Shipping Values Upon Add New Customer @ WP Dashboard
This code is a WordPress action that triggers when a new user registers on a WooCommerce site. It populates certain billing and shipping information for the newly registered user.
- The first line sets up an action hook user_register, which fires when a new user registers on the site. It calls the function bbloomer_populate_billing_shipping_new_customer when this action occurs.
- This function bbloomer_populate_billing_shipping_new_customer accepts one parameter $user_id, which represents the ID of the newly registered user.
- The array $fields contains the names of the fields that need to be populated for billing and shipping information.
- Depending on the field (whether it’s a state or country for billing or shipping), it sets a default value. For states, it sets ‘FL’ (Florida), and for countries, it sets ‘US’ (United States).
- The last line saves the changes made to the customer object, effectively updating the user’s billing and shipping information in the WooCommerce database.
Overall, this code ensures that certain billing and shipping fields are populated with default values for newly registered users on a WooCommerce site.
/**
* @snippet Shipping/Billing Defaults @ WooCommerce New User
* @tutorial Get CustomizeWoo.com FREE
* @author Rodolfo Melogli
* @compatible WooCommerce 8
* @community Join https://businessbloomer.com/club/
*/
add_action( 'user_register', 'bbloomer_populate_billing_shipping_new_customer' );
function bbloomer_populate_billing_shipping_new_customer( $user_id ) {
$fields = array( 'billing_state', 'billing_country', 'shipping_state', 'shipping_country' );
$customer = new WC_Customer( $user_id );
foreach ( $fields as $prop ) {
if ( is_callable( array( $customer, 'set_' . $prop ) ) ) {
if ( $prop == 'billing_state' || $prop == 'shipping_state' ) {
$customer->{"set_$prop"}( 'FL' );
} elseif ( $prop == 'billing_country' || $prop == 'shipping_country' ) {
$customer->{"set_$prop"}( 'US' );
}
}
}
$customer->save();
}