I have a working function for Bricks Builder forms that will redirect based on user roles. This version is adapted to work on a site that I developed which has multiple login forms, so you will notice that:
$validFormIds
accepts an array- there is an “
if ($formId ==
” section to work out the email field id depending on which form
I have adapted it to recognise whether the login is an email or username using FILTER_VALIDATE_EMAIL
** Edited with improved php logic – Special thanks to @MartinWB for excellent suggestions
<?php
function bricks_login_form_redirect_action( $form ) {
$fields = $form->get_fields();
$formId = $fields['formId'];
// $settings = $form->get_settings();
// Perform some logic here...
$validFormIds = array('lnuzdj', 'hperbv'); // Add all the valid form IDs to this array
if (in_array( $formId, $validFormIds)) {
// error_log('Form ID: ' . $formId);
// get the email address from that field on the login form
if ($formId == 'lnuzdj') {
$login = $fields['form-field-8bbefb'];
} elseif ($formId == 'hperbv') {
$login = $fields['form-field-373317'];
} else {
$login = ''; // Default value if the form ID doesn't match any known form
}
if( $login ) {
// Is the field an email or username? Validate and then get user data
if (filter_var($login, FILTER_VALIDATE_EMAIL)) {
$user = get_user_by('email', $login);
} else {
$user = get_user_by('login', $login);
}
// get user roles
$roles = ( array ) $user->roles;
// error_log('User ID: ' . $user_id);
// error_log('User Roles: ' . implode(', ', $roles));
$base_url = get_home_url();
$role_redirects = [
'administrator' => '/wp-admin/',
'patient' => '/patient-dashboard/',
'clinic_admin' => '/clinic-admin/',
'customer' => '/shop/',
'subscriber' => '/shop/',
'shop_manager' => '/wp-admin/',
];
$default_redirect = '/shop/';
$redirect_to = $base_url . $default_redirect; // Default redirection
foreach ($role_redirects as $role => $path) {
if (in_array($role, $roles)) {
$redirect_to = $base_url . $path;
break;
}
}
// error_log('Redirecting to: ' . $redirect_to);
$form->set_result([
// 'action' => 'my_custom_redirect',
'type' => 'redirect',
'redirectTo' => $redirect_to,
'redirectTimeout' => 0
]);
}
}
}
add_action( 'bricks/form/custom_action', 'bricks_login_form_redirect_action', 10, 1 );
Form Action Settings:
If anyone has improvements let me know