Solution:
The hook woocommerce_checkout_registration_required
determines if registration is required during checkout
However the hook you should use to to overwrite the Allow customers to create an account during checkout
setting is woocommerce_checkout_registration_enabled
.
So you get:
// Display Guest Checkout Field
function action_woocommerce_product_options_general_product_data() {
// Checkbox
woocommerce_wp_checkbox( array(
'id' => '_allow_guest_checkout', // Required, it's the meta_key for storing the value (is checked or not)
'wrapper_class' => 'show_if_simple', // For simple products
'label' => __( 'Checkout', 'woocommerce' ), // Text in the editor label
'desc_tip' => false, // true or false, show description directly or as tooltip
'description' => __( 'Allow Guest Checkout', 'woocommerce' ) // Provide something useful here
) );
}
add_action( 'woocommerce_product_options_general_product_data', 'action_woocommerce_product_options_general_product_data', 10, 0 );
// Save Field
function action_woocommerce_admin_process_product_object( $product ) {
// Isset, yes or no
$checkbox = isset( $_POST['_allow_guest_checkout'] ) ? 'yes' : 'no';
// Update meta
$product->update_meta_data( '_allow_guest_checkout', $checkbox );
}
add_action( 'woocommerce_admin_process_product_object', 'action_woocommerce_admin_process_product_object', 10, 1 );
// Remove registration from WooCommerce checkout
function filter_woocommerce_checkout_registration_enabled( $registration_enabled ) {
// WC Cart
if ( WC()->cart ) {
// NOT empty
if ( ! WC()->cart->is_empty() ) {
// Loop through cart items
foreach ( WC()->cart->get_cart() as $cart_item ) {
// Get meta
$allow_guest_checkout = $cart_item['data']->get_meta( '_allow_guest_checkout', true );
// Compare
if ( $allow_guest_checkout == 'yes' ) {
$registration_enabled = false;
break;
}
}
}
}
return $registration_enabled;
}
add_filter( 'woocommerce_checkout_registration_enabled', 'filter_woocommerce_checkout_registration_enabled', 10, 1 );
Note: This answer assumes that Allow customers to place orders without an account
is enabled