Ad

Require Registration In WooCommerce For Specific Product

- 1 answer

It's straightforward to required registration globally in WooCommerce settings but for most of the products we sell, it's not necessary and I would rather restrict the logged in users.

However for one product I would like to require registration.

Something like

$product_id = $product->get_id();

if ($product_id !== 1024) {

  remove_action( 'woocommerce_before_checkout_registration_form', 'action_woocommerce_checkout_registration_form', 10, 1 );

}

but it's obviously not that simple. Any ideas?

Ad

Answer

This answer assumes that WooCommerce > Settings > Accounts & privacy > Allow customers to place orders without an account is enabled

You can then use the following code, that will ensure that when there is 1 or more productID's in the shopping cart, registration during checkout will be required

function filter_woocommerce_checkout_registration_required( $bool_value ) {
    // Several can be added, separated by a comma
    $product_ids = array ( 30, 813 );
    
    // Loop through cart items
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        // Product ID from cart item in specific array
        if ( in_array( $cart_item['product_id'], $product_ids ) ) {
            // Registration_required
            $bool_value = true;
                    
            // Break loop
            break;
        }
    }

    return $bool_value;
}
add_filter( 'woocommerce_checkout_registration_required', 'filter_woocommerce_checkout_registration_required', 10, 1 );
Ad
source: stackoverflow.com
Ad