問題描述
In apply_filters()
apply_filters( $tag, $value, $var ... );
我的頭圍繞著 $value 和 $var 有困難。我讀了 codex,聽起來像 $value 可以修改,$var 沒有,但我還沒有發現這個在野外的例子。它似乎被用作傳遞變數的一種方式。在這種情況下,與 $var 有什麼區別?
最佳解決方案
嘗試看更好的名稱的功能:
apply_filters(
$filter_name, // used for add_filter( $filter_name, 'callback' );
$value_to_change, // the only variable whose value you can change
$context_1, // context
$context_2 // more context
);
所以當這個函式叫做:
// wp-login.php line 94
apply_filters( 'login_body_class', $classes, $action );
您可以使用 …
add_filter( 'login_body_class', 'function_to_change_login_body_class', 10, 2 );
… 並獲取傳遞給該函式的兩個變數。你返回第一個,第二個提供更多的上下文:
function function_to_change_login_body_class( $classes, $action )
{
if ( 'login' === $action )
$classes[] = 'foo';
if ( 'postpass' === $action )
$classes[] = 'bar';
return $classes;
}
額外的變數是讓您的決策更容易,也不要改變。
次佳解決方案
什麼是過濾器?
Filters are functions that WordPress passes data through, at certain points in execution, just before taking some action with the data (such as adding it to the database or sending it to the browser screen). Filters sit between the database and the browser (when WordPress is generating pages), and between the browser and the database (when WordPress is adding new posts and comments to the database); most input and output in WordPress passes through at least one filter. WordPress does some filtering by default, and your plugin can add its own filtering.
掛入過濾器
為了讓使用者更改一些特定的資料 (一個值,一個功能的輸出等),透過 apply_filters 功能提供濾波器鉤。這些過濾器鉤子包括過濾器的名稱 (或標籤) 和至少用於過濾 (即以某種方式改變) 資料的功能名稱。
要更改帖子的標題,可以使用 the_title 過濾器鉤子,其定義如下:
apply_filters( 'the_title', $title, $id );
這意味著,該過濾器具有標籤/名稱 the_title,第一個引數 $title 是要更改的資料 (即後標題),第二個引數 $id 是額外的資訊 (在這種情況下為帖子 ID) 。
例如,要顯示 UPPERCASE 中每個帖子的標題,可以使用以下行:
add_filter('the_title', 'strtoupper');
如果我們來看看 add_filter 函式,我們看到它定義如下:
add_filter( $tag, $function_to_add, $priority, $accepted_args );
我們只指定了第一個和第二個 (必需) 引數,而第三個和第四個引數被設定為其各自的預設值 (即 10 和 1) 。
更復雜的過濾器
如果您只想過濾某個帖子,您可以使用額外的資訊 (在此過濾器的情況下:ID) 。為此,您必須指定引數數量 (在這種情況下為 2),為了再次執行此操作,必須指定優先順序引數 (該引數位於引數數量之前) 。
假設我們只想影響標題為 42 的標題,那麼它看起來像這樣:
add_filter('the_title', 'my_strtoupper', 10, 2);
function my_strtoupper($title, $id) {
if (42 === $id) return strtoupper($title);
return $title;
} // function my_strtoupper
在這種情況下,我們必須指定所有四個可用引數。
我有什麼引數?
要識別某個過濾器的可用引數的數量,您必須查詢它在哪裡定義 (在這種情況下是:here) 。
參考文獻:
-
apply_filters功能 -
add_filter功能
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。