如果您必须在任何页面中替换或翻译functions.php中的一个字符串或文本,那么这段代码在WordPress中工作得很好:
//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;
}如何使用相同的代码替换多个字符串或文本?
在我的例子中,我用两个不同的按钮替换了文本,为了做到这一点,我使用了两次相同的代码:
//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;
}那么,有办法用一个函数替换多个字符串吗?
发布于 2021-02-16 08:41:20
您可以使用如下所示的开关情况:
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;
}还没测试过。
发布于 2021-02-16 09:09:06
Call the function inside the loop
and pass the parameter by creating an array or if you from a database similar its work.
e.g:
$array = array(
array(
'text_to_replace' => 'Dummy',
'new_text' => 'Test',
'text_content'=> 'Dummy content string'
))
//function
function change_cancellation_btn($text_to_replace, $new_text, $text_content){
$changedText = str_ireplace($text_to_replace, $new_text, $text_content);
return $changedText;
}
Now call the change_cancellation_btn by running the loop of the array by passing multiple contents.发布于 2021-02-24 11:24:09
最新消息。这对我来说更好,因为它也替换/翻译了管理后端中的所有字符串:
add_filter( 'gettext', 'dirty_translate' );
add_filter( 'ngettext', 'dirty_translate' );
function dirty_translate( $translated ) {
$words = array(
// 'word to translate' => 'translation'
'Dashboard' => 'Foo',
'Add new' => 'Bar'
);
$translated = str_ireplace( array_keys($words), $words, $translated );
return $translated;
}参考文献:Wordpress replace all ocurrances of the string in admin
https://stackoverflow.com/questions/66220947
复制相似问题