Redirect Users After Login in Drupal

There are a lot of modules out there for redirecting users on login, but they're pretty heavy if all you want to do is redirect the user. In a module:

<?php

/**
 * Implements hook_user_login().
 */
function mymodule_user_login(&$edit, $account) {

  // Redirect them to their edit page.
  $edit['redirect'] = 'user/' . $account->uid . '/newsfeed';
}

That would just redirect the user to their edit page instead. However, other modules may have set $_GET['destination'], which may override that.

You can explicitly remove that destination to make this work as follows. The example includes only redirecting the user if they have a given permission.

/**
 * Implements hook_user_login().
 */
function mymodule_user_login(&$edit, $account) {

  // Check if the user has a permission
  if (user_access('some permission', $account)) {

    // Check if this is the frontpage.
    if (drupal_is_front_page()) {

      // Remove the $_GET redirect so they make it to the redirect.
      unset($_GET['destination']);
    }

    // Redirect them to their edit page
    $edit['redirect'] = 'user/' . $account->uid . '/newsfeed';
  }
}


Comments

memi's picture

memi

Nice but where I should put this code? In what file? Where? Such tutorial is useless.