Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save petronioamaral/af7e81236e7232cbb0064225f96b15e5 to your computer and use it in GitHub Desktop.
Save petronioamaral/af7e81236e7232cbb0064225f96b15e5 to your computer and use it in GitHub Desktop.
WordPress | Translate string with PHP function
<?php
// option 1, to change text site wide
add_filter( 'gettext', 'fs_translate_strings_1', 20, 3 );
function fs_translate_strings_1( $translation, $text, $domain ) {
// STRING 1
$translation = str_ireplace( 'My Old Text', 'My New Text', $translation );
// STRING 2
$translation = str_ireplace( 'Old Text', 'New text', $translation );
return $translation;
}
// option 2, to change text sitewide and create a new translatable version of it
add_filter( 'gettext', 'fs_translate_strings_2', 20, 3 );
function fs_translate_strings_2( $translation, $text, $domain ) {
switch ( $translation ) {
case 'My Old Text' :
$translation = __( 'My New Text', 'your-new-text-domain' );
break;
case 'Old Text' :
$translation = __( 'New Text', 'your-new-text-domain' );
break;
}
return $translation;
}
// option 3, to change text within a particular domain only, and only on the Checkout page
add_filter( 'gettext', 'fs_translate_strings_3', 20, 3 );
function fs_translate_strings_3( $translation, $text, $domain ) {
if ( 'woocommerce' === $domain && is_checkout() ) {
if ( 'My Old Text' === $text ) {
$translation = 'My New Text';
}
}
return $translation;
}
// example of option 3 for Events Calendar event pages
// change some The Events Calendar text, and only on certain pages
add_filter( 'gettext', 'fs_translate_strings_events', 20, 3 );
function fs_translate_strings_events( $translation, $text, $domain ) {
if ( 'the-events-calendar' === $domain && is_single() && 'tribe_events' == get_post_type() ) {
if ( '+ Google Map' === $text ) {
$translation = 'Get Directions';
}
if ( 'Venue' === $text ) {
$translation = 'Location';
}
}
return $translation;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment