3

After any user logs in, I want to show all users the same page, but in their prefered language. So, I want to redirect the user to the page URL with the language appended, like http://example.com/pt or http://example.com/en.

What is the best way make this redirect?

8

You can use the hook_user_login which is called after a user successfully log in to the website. This hook passes the user object as an argument that you can use to retrieve the user language.

For the languages, you can make use of the language_list, which returns an array with the defined languages in your Drupal website. And for the redirect, drupal_goto does the job.

Here is some sample code that could help you further:

function YOURMODULE_user_login(&$edit, $account)
{
    // retrieve user language
    $user_language = $account->language;

    // don't do anything if no language is defined
    if (!$user_language) {
        return;
    }

    // verify if language exists
    $languages = language_list();
    if (!isset($languages[$user_language])) {
        return;
    }

    // verify if language is enabled
    if (!$languages[$user_language]->enabled) {
        return;
    }

    // redirect to preferred language homepage
    drupal_goto('<front>', array(
        'language' => $languages[$user_language],
    ));
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.