問題描述
每當 WordPress 中的管理員激活插件時,在重新加載插件頁面時,成功啓動報告”Plugin Activated” 後會顯示一條通知。
有沒有辦法更改出現在管理通知中的文本,還是必須使用我自己的自定義消息?另外,如果我必須使用自定義消息,這會抑制默認的”Plugin Activated” 消息嗎?
相關問題:
重複:
感謝 Pieter 的發現:
其他資源:
Note
Rememember that although ‘gettext’ filter is only applied during calls to the
translate()function,translate()is used by virtually all other i18n functions in i18n.php. These include all of the functions listed here in this post on “Gettext Syntax“.
最佳解決方案
你可以試試這個:
is_admin() && add_filter( 'gettext',
function( $translated_text, $untranslated_text, $domain )
{
$old = array(
"Plugin <strong>activated</strong>.",
"Selected plugins <strong>activated</strong>."
);
$new = "Captain: The Core is stable and the Plugin is <strong>activated</strong> at full Warp speed";
if ( in_array( $untranslated_text, $old, true ) )
$translated_text = $new;
return $translated_text;
}
, 99, 3 );
修改你的喜好的消息:
我們可以進一步改進:
如果只想激活/wp-admins/plugins.php 頁面上的過濾器,可以使用以下代碼:
add_action( 'load-plugins.php',
function(){
add_filter( 'gettext', 'b2e_gettext', 99, 3 );
}
);
有:
/**
* Translate the "Plugin activated." string
*/
function b2e_gettext( $translated_text, $untranslated_text, $domain )
{
$old = array(
"Plugin <strong>activated</strong>.",
"Selected plugins <strong>activated</strong>."
);
$new = "Captain: The Core is stable and the Plugin is <strong>activated</strong> at full Warp speed";
if ( in_array( $untranslated_text, $old, true ) )
{
$translated_text = $new;
remove_filter( current_filter(), __FUNCTION__, 99 );
}
return $translated_text;
}
我們在我們進行匹配之後立即刪除 gettext 過濾器回調。
如果我們想檢查 gettext 調用的數量,在匹配正確的字符串之前,我們可以使用:
/**
* Debug gettext filter callback with counter
*/
function b2e_gettext_debug( $translated_text, $untranslated_text, $domain )
{
static $counter = 0;
$counter++;
$old = "Plugin <strong>activated</strong>.";
$new = "Captain: The Core is stable and the Plugin is <strong>activated</strong> at full Warp speed";
if ( $untranslated_text === $old )
{
$translated_text = $new;
printf( 'counter: %d - ', $counter );
remove_filter( current_filter(), __FUNCTION__ , 99 );
}
return $translated_text;
}
我得到 301 調用我的安裝:
我可以把它減少到只有 10 調用:
通過在 in_admin_header 鈎子中添加 gettext 過濾器,在 load-plugins.php 鈎子中:
add_action( 'load-plugins.php',
function(){
add_action( 'in_admin_header',
function(){
add_filter( 'gettext', 'b2e_gettext_debug', 99, 3 );
}
);
}
);
請注意,在激活插件時,內部重定向之前,這不會計算 gettext 調用。
要在內部重定向後激活我們的過濾器,我們可以檢查激活插件時使用的 GET 參數:
/**
* Check if the GET parameters "activate" and "activate-multi" are set
*/
function b2e_is_activated()
{
$return = FALSE;
$activate = filter_input( INPUT_GET, 'activate', FILTER_SANITIZE_STRING );
$activate_multi = filter_input( INPUT_GET, 'activate-multi', FILTER_SANITIZE_STRING );
if( ! empty( $activate ) || ! empty( $activate_multi ) )
$return = TRUE;
return $return;
}
並使用如下:
b2e_is_activated() && add_filter( 'gettext', 'b2e_gettext', 99, 3 );
在前面的代碼示例中。
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。



