問題描述

我在這裡搜尋了 add_filter()apply_filters()之間的差異的合適解釋,但找不到。

任何人都可以告訴我在一個上下文中使用 add_filterapply_filters 之前要考慮的資訊或邏輯。

那使得一個命令而不是另一個呢?

  • add_filter 是否正確新增一個函式到等待在一個變數上執行的函式,apply_filters 按順序執行函式?

  • apply_filters 在呼叫引數 (要執行的函式的名稱) 時是否會在佇列中的所有其他函式 (如果存在) 之前執行該函式也是正確的?

最佳解決方案

以下大部分內容可以在 Codex 中找到:


apply_filters

The callback functions attached to filter hook $tag are 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


add_filter

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