couple notes!
No need to check for login status if you are checking capabilities. A visitor (not logged in) only has the exists
capability, nothing more.
Also, wp_redirect()
should always be followed by exit;
in most cases. In your example only the last one was followed by exit;
. Otherwise this could create loops.
I’ve refactored your code a bit, I think this should work:
add_action( 'template_redirect', 'subscribers_redirection' );
function subscribers_redirection() {
$is_product_page = ( is_shop() || is_product_category() || is_product_tag() || is_product() );
$is_logged_in = is_user_logged_in();
$is_subscriber = current_user_can( 'subscriber' );
$is_customer = current_user_can( 'customer' );
$redirect = false;
if ( ! $is_logged_in && $is_product_page ) { // No need to check for user roles if the user isn't logged in.
$redirect = home_url( '/register' );
} else if ( $is_subscriber && ! $is_customer && $is_product_page ) {
$redirect = home_url( '/id-confirmation' );
} else if ( $is_customer && $is_product_page ) { // No need to check for a subscriber if the user already is a customer.
$redirect = home_url( '/shop' );
} else if ( $is_logged_in && is_page( 'register' ) ) {
$redirect = home_url( '/my-account' );
} else if ( ! $is_subscriber && is_page( 'id-confirmation' ) ) {
$redirect = home_url( '/register' );
}
if ( $redirect ) {
wp_redirect( $redirect );
exit;
}
}