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 into 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.
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 the WordPress plugins folder and create a new PHP file in it, add a plugin header and save it.
You should now be able to see the plugin name in the WordPress site.
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 requires google/cloud-translate
To use the PHP client library, we must instantiate the Cloud Translation API client as follows:
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.
- Setting GOOGLE_APPLICATION_CREDENTIALS environment variable, pointing to your service account’s location.
- Code for translating the content in a webpage.
- change language Function (on click event): Whenever a user changes language, the page reloads.
- 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.
- Final addition is the dropdown.