How to add Google Translate to your website ?

If your website is serving to the multiple linguistic users, at some point of time you will need to make sure your website gets translated to the respective language of visitor, so he can understand the contents better.

Within this post, we will explain how to add google translate widget to your website, so that you can use google translation service for translation into different language.

The first step is to add below code just before the closing of the body tag,

<script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
</body>

Now, we will need to add relevant javascript code from google to the place where, we intend to show the google translation widget. Copy below code and paste where you want the translation widget to be seen to website visitor.

<div id="google_translate_element"></div><script type="text/javascript">
function googleTranslateElementInit() {
  new google.translate.TranslateElement({pageLanguage: 'en', includedLanguages: 'bn,gu,hi,kn,ml,mr,pa,ta,te', layout: google.translate.TranslateElement.InlineLayout.HORIZONTAL}, 'google_translate_element');
}
</script>

The above code shows only the selected Indian languages into the dropdown menu of the translator. If you set the layout to VERTICAL, you will see the “Powered by” message below the dropdown menu, where as HORIZONTAL layout, it will be shown adjacent to dropdown.

If you want to have all the languages shown into dropdown menu, use below code i.e. which removes includedLanguages as shows all default languages supported by google translate.

<div id="google_translate_element"></div><script type="text/javascript">
function googleTranslateElementInit() {
  new google.translate.TranslateElement({pageLanguage: 'en'}, 'google_translate_element');
}
</script>

Below code is the final example, which also shows how you can track the translations using the google analytics id.

<!DOCTYPE html>
<html lang="en-US">
<body>
 
<h4> Vegetables are parts of plants that are consumed by humans or other animals as food. The original meaning is still commonly used and is applied to plants collectively to refer to all edible plant matter, including the flowers, fruits, stems, leaves, roots, and seeds. Reference: Wikipedia </h4>
 
<div id="google_translate_element"></div><script type="text/javascript">
function googleTranslateElementInit() {
  new google.translate.TranslateElement({pageLanguage: 'en', includedLanguages: 'bn,gu,hi,kn,ml,mr,pa,ta,te', layout: google.translate.TranslateElement.InlineLayout.HORIZONTAL, gaTrack: true, gaId: 'YOUR_GOOGLE_ANALYTICS_ID'}, 'google_translate_element');
}
</script>
 
 
 
<script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
</body>
Follow Lynxbee

Leave a Reply / Ask Question