Right Method to Get the Language Code for a Given Drupal 7 Entity

While programming for Drupal, it is a very common scenario to get the language code for a given entity. A bad practice being followed by many programmers is hard-coding the value und directly as language code. Some programmers will take languag property of the entity object, this only works for entity of type node and entities that have property named language as entity key for language.

If you want to follow the right method or if you are developing a generic module that deals with variety of entity types then you need to use the function entity_language(). It just requires to pass the type of entity and entity object itself as parameters.

$language_code = entity_language('node', $entity);

It will return proper language code for given entity or NULL if entity has no language support. The function do its job by inspecting entity info for that entity type. This entity info might have already statically cached while you loaded the entity before, so it will not issue an extra database query in that case.