questions

Replace multiple strings or texts

Rate this post

This code within functions.php works very fine if you have to replace or translate one string or text in WordPress, in any page:

//The filters.. both are required.
add_filter('gettext', 'change_cancellation_btn');
add_filter('ngettext', 'change_cancellation_btn');

//function
function change_cancellation_btn($cancellation_btn){
$cancellation_btn = str_ireplace('text to replace', 'new text', $cancellation_btn);
return $cancellation_btn;
}

How can I use the same code to replace multiple strings or texts?

In my case I replaced the texts in two different buttons and to do it I used the same code twice:

//The filters.. both are required.
add_filter('gettext', 'change_cancellation_btn');
add_filter('ngettext', 'change_cancellation_btn');

//function button 1
function change_cancellation_btn($cancellation_btn){
$cancellation_btn = str_ireplace('text 1 to replace', 'new text 1', $cancellation_btn);
return $cancellation_btn;
}


//The filters.. both are required.
add_filter('gettext', 'change_nocancellation_btn');
add_filter('ngettext', 'change_nocancellation_btn');

//function button 2
function change_nocancellation_btn($nocancellation_btn){
$nocancellation_btn = str_ireplace('text 2 to replace', 'new text 2', $nocancellation_btn);
return $nocancellation_btn;
}

So, is there a way to replace multiple strings with one function?

 

✔️Solution:

You can use switch case like below:

add_filter( 'gettext', 'theme_change_comment_field_names', 20, 3 );
function theme_change_comment_field_names( $translated_text, $text, $domain ) {
  
    switch ( $translated_text ) {
 
        case 'text 1 to replace' :
 
            $translated_text = __( 'new text 1', 'theme_text_domain' );
            break;
 
        case 'text 2 to replace' :
 
            $translated_text = __( 'new text 2', 'theme_text_domain' );
            break;
    }    
 
    return $translated_text;
}

Leave a Reply

Your email address will not be published.

Back to top button