How to build a WordPress Translation Plugin using Google Cloud Translation API

In this demo, we will build a WordPress plugin that calls the Google Translation API. Through this API, you can translate text into all major languages. In addition to this, the translation service is affordable. Check out their pricing for a better understanding.
Using the Google Cloud APIs, we can also integrate in other programming languages to some extent. We can use Translation by making direct REST over HTTP requests but Google Cloud provides supported libraries in all major programming languages. All we need to do is call their APIs along with the data. It also provides types and methods that you may use directly when using any Cloud API. For this demo, we will be using the PHP client library.

Authentication:

In order to use Google Cloud services, you need to authenticate your Google account. There are multiple options for authentication, but it is recommended that you use service accounts for authentication. You are required to create a service account and download the JSON file containing your credentials. You must also enable the Cloud Translation API via the API Library section.

Setting up WordPress Plugin:

  • Create a new folder in WordPress plugins folder and create a new php file in it, add a plugin header and save it.
translation api

You should now be able to see the plugin name in the WordPress site.

plugin

To install the Translation API’s PHP client library, we need to run the following command in the WordPress plugin’s folder. You can download composer here if you haven’t already.

  • composer require google/cloud-translate
composer

To use the PHP client library, we must instantiate the Cloud Translation API client as follows:
use Google\Cloud\Translate\TranslateClient;

Next Steps:

Once everything is set up, we can start adding in our logic. For this demo, we will just be translating the content and title of a webpage.

  1. Setting GOOGLE_APPLICATION_CREDENTIALS environment variable, pointing to your service account’s location.
GOOGLE_APPLICATION_CREDENTIALS
  1. Code for translating the content in a webpage.
translate
  1. changeLanguage Function (on click event): Whenever a user changes language, the page reloads.
change-language
  1. Onload property, processes the load events after the element has finished loading. It will basically run the function as soon as the webpage has been loaded. In our case, it is translation.
window
  1. Final addition is the dropdown.
dropdown

Watch video

Thought Leadership