add_filter

函式
add_filter ( $hook_name, $callback, $priority = 10, $accepted_args = 1 )
引數
  • (string) $hook_name The name of the filter to add the callback to.
    Required:
  • (callable) $callback The callback to be run when the filter is applied.
    Required:
  • (int) $priority Optional. Used to specify the order in which the functions associated with a particular filter are executed. Lower numbers correspond with earlier execution, and functions with the same priority are executed in the order in which they were added to the filter. Default 10.
    Required:
    Default: 10
  • (int) $accepted_args Optional. The number of arguments the function accepts. Default 1.
    Required:
    Default: 1
返回值
  • (true) Always returns true.
定義位置
相關方法
did_filterhas_filterdoing_filterapply_filtersadd_feed
引入
0.71
棄用
-

add_filter: 這個函式用來向WordPress新增一個新的過濾器: 該函式有三個引數:鉤子名稱、回撥函式和過濾器的優先順序。

為一個過濾器鉤子新增一個回撥函式。

WordPress提供過濾器鉤子,允許外掛在執行時修改各種型別的內部資料。

一個外掛可以通過繫結一個回撥函式到一個過濾器鉤子來修改資料: 當過濾器後來被應用時,每個繫結的回撥函式按優先順序執行,並有機會通過返回一個新值來修改一個值。

下面的例子顯示了一個回撥函式是如何繫結到過濾器鉤子上的。

注意`$example`被傳遞給回撥,(可能)被修改,然後返回:

function example_callback( $example ) {
// Maybe modify $example in some way.
return $example;
}
add_filter( ‘example_filter’, ‘example_callback’ );

繫結的回撥可以接受從無到有的引數總數,這些引數在相應的apply_filters()呼叫中作為引數傳遞。

換句話說,如果一個apply_filters()呼叫傳遞了四個引數,與之繫結的回撥可以不接受任何引數(與1相同),也可以接受最多四個引數。重要的是,`$accepted_args’值必須反映被繫結的回撥*實際*選擇接受的引數數量。如果回撥沒有接受任何引數,則被認為與接受1個引數的情況相同。比如說:

// Filter call.
$value = apply_filters( ‘hook’, $value, $arg2, $arg3 );

// Accepting zero/one arguments.
function example_callback() {

return ‘some value’;
}
add_filter( ‘hook’, ‘example_callback’ ); // Where $priority is default 10, $accepted_args is default 1.

// Accepting two arguments (three possible).
function example_callback( $value, $arg2 ) {

return $maybe_modified_value;
}
add_filter( ‘hook’, ‘example_callback’, 10, 2 ); // Where $priority is 10, $accepted_args is 2.

*注意:* 無論回撥是否有效,該函式都將返回true。這取決於你的照顧。這樣做是為了優化,所以一切都儘可能的快。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
function add_filter( $hook_name, $callback, $priority = 10, $accepted_args = 1 ) {
global $wp_filter;
if ( ! isset( $wp_filter[ $hook_name ] ) ) {
$wp_filter[ $hook_name ] = new WP_Hook();
}
$wp_filter[ $hook_name ]->add_filter( $hook_name, $callback, $priority, $accepted_args );
return true;
}
function add_filter( $hook_name, $callback, $priority = 10, $accepted_args = 1 ) { global $wp_filter; if ( ! isset( $wp_filter[ $hook_name ] ) ) { $wp_filter[ $hook_name ] = new WP_Hook(); } $wp_filter[ $hook_name ]->add_filter( $hook_name, $callback, $priority, $accepted_args ); return true; }
function add_filter( $hook_name, $callback, $priority = 10, $accepted_args = 1 ) {
	global $wp_filter;

	if ( ! isset( $wp_filter[ $hook_name ] ) ) {
		$wp_filter[ $hook_name ] = new WP_Hook();
	}

	$wp_filter[ $hook_name ]->add_filter( $hook_name, $callback, $priority, $accepted_args );

	return true;
}

常見問題

FAQs
檢視更多 >