Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save twoelevenjay/80294a635969a54e4693 to your computer and use it in GitHub Desktop.
Save twoelevenjay/80294a635969a54e4693 to your computer and use it in GitHub Desktop.
Allow admins to manually enter new WooCommerce orders from the frontend checkout field.
<?php
// Allow admins to manually enter new WooCommerce orders from the frontend checkout field.
// Hook the woocommerce_checkout_customer_id filter found in the WC_Checkout class.
add_filter( 'woocommerce_checkout_customer_id', 'change_current_user_id_to_new_user' );
function change_current_user_id_to_new_user( $user_id ) {
//Check if logged in user is admin.
if ( current_user_can( 'manage_options' ) ) {
// grab the $_POST values from the checkout form needed to create a new user.
$checkout_email = $_POST['billing_email'];
$first_name = $_POST['billing_first_name'];
$last_name = $_POST['billing_last_name'];
// Check if an exisiting user already uses this email address.
$user = get_user_by( 'email', $checkout_email );
// If the user email already exists then pass along their user ID, otherwise create a new user.
if ( $user ) {
$new_user_id = $user->ID;
}else{
// Randomly generate a password.
$password = wp_generate_password( 12, false );
// Use the email for username and email to avoid conflicts.
$new_user_id = wp_create_user( $checkout_email, $password, $checkout_email );
// Add a first name, last name, and the customer user role to the new user.
wp_update_user( array( 'ID' => $new_user_id, 'first_name' => $first_name, 'last_name' => $last_name, 'role' => 'customer' ) );
}
// Make sure nothing went wrong.
if ( !is_wp_error( $new_user_id ) ) {
$user_id = $new_user_id;
}
}
// Be sure toreturn the user ID.
return $user_id;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment