wordpress中add_action和add_filter


add_action( string $tag, callable $function_to_add, int $priority = 10,int $accepted_args = 1 )

官網是這么說的:在一個特定的動作上掛鈎一個函數。

那么就有對應的執行這個特定動作的函數:

do_action( string $tag,  $arg = '' )

在我理解他有這麽一個好處,就是把多個不同運用的函數一起執行,進行輸出。

add_filter( string $tag, callable $function_to_add, int $priority = 10, int $accepted_args = 1 )

add_filter跟add_action類似,在一個特定的動作上掛鈎一個方法或函數,主要的區別就是有返回值。通過官網的例子可以看出:

// 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.

添加靜態方法:

add_filter( 'media_upload_newtab', array( 'My_Class', 'media_upload_callback' ) );

添加函數:

add_filter( 'media_upload_newtab', array( $this, 'media_upload_callback' ) );

傳遞的第二個參數也可以是一個閉包:

add_filter( 'the_title', function( $title ) { return '<strong>' . $title . '</strong>'; } );

與此對應的有apply_filter調用鈎子上的 函數或方法

apply_filters( string $tag, mixed $value )

add_action與add_filter 主要的區別就是一個有返回值一個沒有返回值。

apply_filter和do_action都是執行鈎子上掛載的函數集。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM