問題描述
每當 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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。



