Solution:
You don’t need to wait until the item is being added and then re-direct. You can validate whether the item can be added on the woocommerce_add_to_cart_validation
filter. The rest of your logic is pretty valid.
add_filter( 'woocommerce_add_to_cart_validation', 'so_34505885_add_to_cart_validation' ), 10, 6 );
function so_34505885_add_to_cart_validation( $passed_validation, $product_id, $product_quantity, $variation_id = '', $variations = array(), $cart_item_data = array() ) {
// If product tagged as for club members
if (has_term( 'club-only', 'product_tag', $product_id )){
$current_user = wp_get_current_user();
if ( !$current_user || $current_user->club_card_number == ''){
wc_add_notice( sprintf( __( 'You must be a club member to purchase this product.', 'your-plugin-textdomain' ), $mnm_item->get_title() ), 'error' );
$passed_validation = false;
}
}
return $passed_validation;
}
Or even better still you could completely prevent the add to cart buttons from even working on items that can’t be purchased by toggling whether or not the product is purchasable.
add_filter( 'woocommerce_is_purchasable', 'so_34505885_is_purchasable' ), 10, 2 );
function so_34505885_is_purchasable( $purchasable, $product_id ) {
// If product tagged as for club members
if (has_term( 'club-only', 'product_tag', $product_id )){
$current_user = wp_get_current_user();
if ( !$current_user || $current_user->club_card_number == ''){
wc_add_notice( sprintf( __( 'You must be a club member to purchase this product.', 'your-plugin-textdomain' ), $mnm_item->get_title() ), 'error' );
$purchasable = false;
}
}
return $purchasable;
}