Redirect user to a target page upon logging in

Public

In my side project, my client wants the site users to be redirected to the Workbench page upon logging in. I've tried implementing it first using hook_user_login() with drupal_goto() but it seems to be tricky and unstable. I found out that it's easier to implement it by using hook_form_alter() and the form's #action property.

The #action property is usually used to set the path to which the form will be submitted. Hence, we could alter the behavior of the User Login block by overriding the default #action property and setting its new target URL, effectively redirecting the authenticated user to the desired page.

</> CopyGet raw version
php
  1. /**
  2.  * Implements hook_form_alter().
  3.  */
  4. function my_module_form_alter(&$form, &$form_state, $form_id) {
  5. if ($form_id == 'user_login_block') {
  6. // Set your desired target page/URL here.
  7. $target_url = 'admin/workbench';
  8.  
  9. $form['#action'] = url($target_url);
  10. }
  11. }