translate woocommerce product category descriptions using Google Translasion API

62 Views Asked by At

I'm looking for an answer how to translate woocommerce product category descriptions using Google Translasion API without making the whole site multilingual.

I am trying to use the following code:

<?php
$api_key = 'AIzaSyBOti4mM-6x9xxxxxxxxxxxxxxxxxx';

function translate_category_names_using_google_translate($api_key, $source_language, $target_language, $category_name) {

  $url = "https://translation.googleapis.com/language/translate/v2?key=$api_key&source=$source_language&target=$target_language&q=$category_name";

  $response = wp_remote_get($url);

  if (is_wp_error($response)) {
    return false;
  }

  $json = json_decode($response['body'], true);

  return $json['translations'][0]['translatedText'];
}

function translate_category_names() {

  $categories = wc_get_categories();

  foreach ($categories as $category) {

    $name = $category->name;

    $translated_name = translate_category_names_using_google_translate($api_key, 'pl', 'lt', $name);
    if (!empty($translated_name)) {
      $category->name = $translated_name;

      echo $translated_name . "\n";

      $category->save();
    }
  }
}

translate_category_names();
 
?>

but I get a reply from cosole with error 500.

Is there another way to translate the product category names and the product names themselves without plugins that redesign the whole site? I am using the WP All Import plugin, maybe it has a feature I haven't found yet?

0

There are 0 best solutions below