您无需等到项目被添加后再重新定向。您可以验证是否可以在 woocommerce_add_to_cart_validation 过滤器上添加项目。您的其余逻辑非常有效。
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;
}
或者甚至更好的是,您甚至可以通过切换产品是否可购买来完全阻止添加到购物车按钮甚至对无法购买的商品起作用。
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;
}