Limit the views results to current site language when using entity translation in Drupal 7

Last updated on 15/09/2016
/**
 * Limit the views results to current site language.
 *
 * @param \QueryAlterableInterface $query
 */
function HOOK_query_alter(QueryAlterableInterface $query) {
if (isset($query->alterTags['MY_VIEWS_TAG'])) {
    // Determine base table and base table key of the query.
    foreach ($query->getTables() as $table_key => $table_info) {
      if ($table_info['join type'] == NULL) {
        $base_table = $table_info['alias'];
      }
    }
    if (!isset($base_table)) {
      return;
    }
 
    // For base table 'node' queries, do the Entity Translation filtering.
    if ($base_table == 'node') {
      $language = $GLOBALS['language']->language;
      $base_schema = drupal_get_schema($base_table);
      $base_field = $base_schema['primary key'][0];
      if (!isset($base_field)) {
        return;
      }
 
      $query->addTag('entity_translation_filtered');
 
      $et_table = $query->leftJoin('entity_translation', 'et', "et.entity_type = :base_table AND et.entity_id = $base_table.$base_field AND et.language = :language", array(
        ':base_table' => $base_table,
        ':language' => $language
      ));
      $field_base_language = $query->addField($base_table, 'language');
 
      $field_et_language = $query->addField($et_table, 'language', 'et_language');
      $field_et_status = $query->addField($et_table, 'status', 'et_status');
      $field_et_translate = $query->addField($et_table, 'translate', 'et_translate');
 
      $query->condition(db_or()
        ->condition($base_table . '.' . $field_base_language, LANGUAGE_NONE)
        ->condition($base_table . '.' . $field_base_language, $language)
        ->condition(db_and()
          ->condition($et_table . '.' . 'language', $language)
          ->condition($et_table . '.' . 'status', 1)
        ));
    }
  }
}