Last active
November 21, 2023 12:38
-
-
Save Garconis/01ef6ef554777c1fea3b4b9138c3db2d to your computer and use it in GitHub Desktop.
WordPress | Translate string with PHP function
This file contains hidden or 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
<?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