Scopri come usare le funzioni gettext per rendere i testi di temi e plugin traducibili in WPML.
Per assicurarti che i testi di temi e plugin siano traducibili e appaiano correttamente sul tuo sito, devi soddisfare due condizioni:
- Racchiudi i testi in una funzione gettext
- Includi un argomento text domain
Nozioni di base su gettext
Considera la seguente stringa, “Thank you!”, che appartiene al dominio “my-plugin-domain”:
__( 'Thank you!', 'my-plugin-domain' );
Per stampare la stringa nel browser, usa la funzione _e() :
_e( 'Thank you!', 'my-plugin-domain' );
Quando usi l’HTML, racchiudila tra i tag HTML:
<h2><?php _e( 'Thank you!', 'my-plugin-domain' ); ?></h2>
Se hai un link separato dal testo circostante, usa la funzione esc_html_e():
<a href="http://wpml.org/" ><?php esc_html_e( 'Translated with WPML', 'my-domain' ); ?></a>
Migliori pratiche per gettext
1. Non racchiudere mai una variabile o una costante in una funzione gettext
Questo renderà le stringhe non scansionabili e, di conseguenza, non traducibili.
Errato
<?php
if ( $morning ) {
define( 'GREETING', 'Good morning' );
} else {
define( 'GREETING', 'Good afternoon' );
}
_e( GREETING, 'my-domain' );
?>
Corretto
<?php
if ( $morning ) {
_e( 'Good morning', 'my-domain' );
} else {
_e( 'Good afternoon', 'my-domain' );
}
?>
2. Esegui l’escape dell’output per sicurezza
Se una stringa viene renderizzata immediatamente nell’output, usa le funzioni di escape, come esc_html_ ed esc_attr_, per proteggerti dagli attacchi XSS.
echo '<div>' . esc_html__( 'Back to homepage', 'my-domain' ) . '</div>';
3. Aggiungi commenti per i traduttori
Questo aiuta i traduttori a capire il contesto in cui compaiono i testi o le variabili.
/* translators: %1$s is status label (e.g. "active" and %2$s is quantity of bits/s (e.g. 12 Gbit/s) */ printf( esc_html__( 'State of your network is %1$s. Maximum download speed is %2$s.', 'my-plugin-domain' ), $state, $speed );
Risorse aggiuntive
Per saperne di più su gettext, consulta il codex ufficiale di WordPress.