問題描述
我在這裏搜索了 add_filter()和 apply_filters()之間的差異的合適解釋,但找不到。
任何人都可以告訴我在一個上下文中使用 add_filter 或 apply_filters 之前要考慮的信息或邏輯。
那使得一個命令而不是另一個呢?
-
add_filter是否正確添加一個函數到等待在一個變量上執行的函數,apply_filters按順序執行函數? -
apply_filters在調用參數 (要運行的函數的名稱) 時是否會在隊列中的所有其他函數 (如果存在) 之前執行該函數也是正確的?
最佳解決方案
以下大部分內容可以在 Codex 中找到:
The callback functions attached to filter hook
$tagare invoked by calling this function. This function can be used to create a new filter hook by simply calling this function with the name of the new hook specified using the $tag parameter.
$value = apply_filters( $tag, $value, $var_1, $var_2, ... );
實質上:您使用 apply_filters 過濾給定的 $value – 相對於值本身以及可選提供的變量 $var_1 通過 $var_n 。
Hook a function to a specific filter action.
add_filter( $tag, $function_to_add, $priority, $accepted_args );
實質上:您使用 add_filter 將自定義函數掛接到給定的過濾器操作 ($tag)(apply_filters) 之前 (或者是內置過濾器操作或源於插件/您的主題) 。
所以,這是一個
虛構
例:
function print_initials( $name ) {
if ( ! is_string( $name ) ) {
return;
}
$fragments = explode( ' ', $name );
/**
* Filter wether to print initials in reverse order.
*
* @param bool $reverse Print initials in reverse order?
*/
if ( apply_filters( 'reverse_initials', FALSE ) ) {
$fragments = array_reverse( $fragments );
}
foreach ( $fragments as $f ) {
echo substr( $f, 0, 1 );
}
}
print_initials( 'Some Guy' ); // outputs: SG
add_filter( 'reverse_initials', '__return_true' );
print_initials( 'Some Guy' ); // outputs: GS
現在,如果我們只是按照我們的函數調用,則首字母從左到右打印,因為這是我們定義為默認行為。
第二次,我們以相反的順序取得首字母,因為過濾器函數__return_true 掛鈎到我們的過濾器動作,總是返回 TRUE,從而使得從右到左輸出首字母。
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。