Created
April 26, 2024 15:07
-
-
Save rwkyyy/b02f862ca2c184419d571a86f541f4c1 to your computer and use it in GitHub Desktop.
Translate each given string in any language, while importing, with WP All Import (via Google Translate) - path should be wp-content/uploads/wpallimport/functions.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function translate_field_with_google($text, $target_language = 'ro') { | |
//usage | |
// [translate_field_with_google({title[1]}, "ro")] where title[1] is the string, and "ro" is the lang. | |
if (!empty($text)) { | |
$api_key = 'YOUR_GOOGLE_TRANSLATE_KEY_HERE'; | |
$url = 'https://translation.googleapis.com/language/translate/v2?key=' . $api_key; | |
$data = array('q' => $text, 'target' => $target_language); | |
$options = array( | |
'http' => array( | |
'header' => "Content-type: application/x-www-form-urlencoded\r\n", | |
'method' => 'POST', | |
'content' => http_build_query($data), | |
), | |
); | |
$context = stream_context_create($options); | |
$result = file_get_contents($url, false, $context); | |
if ($result === FALSE) { | |
return $text; | |
} | |
$response = json_decode($result, true); | |
if (isset($response['data']['translations'][0]['translatedText'])) { | |
return $response['data']['translations'][0]['translatedText']; | |
} else { | |
return $text; | |
} | |
} | |
return $text; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment