Traducir mediante código PHP
Puedes disparar traducciones mediante código PHP dentro de tu aplicación, tema o plugin.
La clase GatoStandalone\GatoAITranslationsForPolylang\Gato proporciona métodos estáticos para disparar traducciones:
| Método | Descripción |
|---|---|
translate | Alias de translateCustomPosts |
translateCustomPosts | Traducir custom posts (páginas, entradas, tipos de entrada personalizados) |
translateTaxonomyTerms | Traducir términos de taxonomía (categorías, etiquetas, taxonomías personalizadas) |
translateMedia | Traducir elementos multimedia (imágenes, documentos, etc.) |
Firma del método
Esta es la firma del método para todos los métodos de traducción:
Solo el parámetro ids es obligatorio. El resto de parámetros, si no se proporcionan, se establecerán con el valor de los Ajustes del plugin.
Puedes encontrar esta clase en el fichero src/Gato.php dentro del plugin.
namespace GatoStandalone\GatoAITranslationsForPolylang;
class Gato
{
/**
* Alias of `translateCustomPosts`
*
* @param int|int[] $ids Array of custom post IDs to translate
* @param string|null $statusToUpdate The status the custom posts must have to be updated
* @param string|null $statusWhenTranslated The status the custom posts will have after translation. Possible values: "draft", "pending", "publish", "private", "current" (i.e. don't modify the status), "same-as-origin" (i.e. copy the status from the origin post)
* @param array<string,string>|null $languageProviders Array of: Key => language code, Value: Provider name, "none" to disable for that language, or "default" to use the default provider
* @return array<string|int>|false Array of custom post IDs that were processed for translation, or `false` if none of the provided IDs was valid
* @throws PolylangNotActiveException
* @throws LicenseNotActiveException
* @throws PluginNotInitializedException
*/
public static function translate(
int|array $ids,
?string $statusToUpdate = null,
?string $statusWhenTranslated = null,
?bool $copyDate = null,
?bool $translateSlugs = null,
?array $languageProviders = null,
?string $defaultTranslationProvider = null,
): array|false;
/**
* Translate custom posts
*
* @param int|int[] $ids Array of custom post IDs to translate
* @param string|null $statusToUpdate The status the custom posts must have to be updated
* @param string|null $statusWhenTranslated The status the custom posts will have after translation. Possible values: "draft", "pending", "publish", "private", "current" (i.e. don't modify the status), "same-as-origin" (i.e. copy the status from the origin post)
* @param array<string,string>|null $languageProviders Array of: Key => language code, Value: Provider name, "none" to disable for that language, or "default" to use the default provider
* @return array<string|int>|false Array of custom post IDs that were processed for translation, or `false` if none of the provided IDs was valid
* @throws PolylangNotActiveException
* @throws LicenseNotActiveException
* @throws PluginNotInitializedException
*/
public static function translateCustomPosts(
int|array $ids,
?string $statusToUpdate = null,
?string $statusWhenTranslated = null,
?bool $copyDate = null,
?bool $translateSlugs = null,
?array $languageProviders = null,
?string $defaultTranslationProvider = null,
): array|false;
/**
* Translate taxonomy terms (categories and tags)
*
* @param int|int[] $ids Array of taxonomy term IDs to translate
* @param array<string,string>|null $languageProviders Array of: Key => language code, Value: Provider name, "none" to disable for that language, or "default" to use the default provider
* @return array<string|int>|false Array of taxonomy term IDs that were processed for translation, or `false` if none of the provided IDs was valid
* @throws PolylangNotActiveException
* @throws LicenseNotActiveException
* @throws PluginNotInitializedException
*/
public static function translateTaxonomyTerms(
int|array $ids,
?bool $translateSlugs = null,
?array $languageProviders = null,
?string $defaultTranslationProvider = null,
): array|false;
/**
* Translate media items
*
* @param int|int[] $ids Array of media item IDs to translate
* @param array<string,string>|null $languageProviders Array of: Key => language code, Value: Provider name, "none" to disable for that language, or "default" to use the default provider
* @return array<string|int>|false Array of media item IDs that were processed for translation, or `false` if none of the provided IDs was valid
* @throws PolylangNotActiveException
* @throws LicenseNotActiveException
* @throws PluginNotInitializedException
*/
public static function translateMedia(
int|array $ids,
?bool $translateSlugs = null,
?array $languageProviders = null,
?string $defaultTranslationProvider = null,
): array|false;
}Contexto de ejecución
Ejecuta cualquiera de los métodos solo después de que el plugin se haya inicializado. Esto ocurre en diferentes hooks, según el contexto:
| Contexto | Hook |
|---|---|
| Frontend | Hook de acción 'wp' |
| Admin | Hook de acción 'wp_loaded' |
| REST API | Hook de filtro 'rest_jsonp_enabled' |
Ejemplos de ejecución
Ejecutar traducciones desde dentro de cada uno de los hooks de WordPress:
use GatoStandalone\GatoAITranslationsForPolylang\Exception\AbstractGatoAITranslationsForPolylangException;
// Frontend
add_action('wp', function() {
try {
Gato::translateCustomPosts(123);
} catch (AbstractGatoAITranslationsForPolylangException $e) {
error_log($e->getMessage());
}
});
// Admin
add_action('wp_loaded', function() {
try {
Gato::translateTaxonomyTerms([456, 789]);
} catch (AbstractGatoAITranslationsForPolylangException $e) {
error_log($e->getMessage());
}
});
// REST API
add_filter('rest_jsonp_enabled', function(mixed $value): mixed {
try {
Gato::translateMedia([101, 102]);
} catch (AbstractGatoAITranslationsForPolylangException $e) {
error_log($e->getMessage());
}
return $value;
});Si tienes la certeza de que:
- Polylang está activo
- Dispones de una licencia válida para el plugin
- El plugin se ha inicializado (es decir, los hooks anteriores ya se han ejecutado)
…entonces puedes ejecutar las traducciones sin necesidad de comprobar excepciones:
Gato::translate(123); // Same as `translateCustomPosts`
Gato::translateCustomPosts(123);
Gato::translateTaxonomyTerms([456, 789]);
Gato::translateMedia([101, 102]);