Heim  >  Artikel  >  Backend-Entwicklung  >  详解WordPress中添加和执行动作的函数使用方法_php技巧

详解WordPress中添加和执行动作的函数使用方法_php技巧

WBOY
WBOYOriginal
2016-05-16 20:01:161441Durchsuche

add_action()(添加动作)
add_action() 函数用来挂载一个函数到动作钩子上。

用法

add_action( $tag, $function_to_add, $priority, $accepted_args );

参数

$hook

(字符串)(必须)挂载函数的动作名称。

默认值:None

$function_to_add

(回调函数)(必须)挂载的函数,直接填写字符串形式的函数名即可。

默认值:None

$priority

(整数)(可选)动作执行的优先级,数值越小越先被执行。

默认值:10

$accepted_args

(整数)(可选)回调函数接收几个参数。

默认值:1

返回值

(布尔)始终返回 True.

例子

给 wp_head 动作挂载一个函数,在 head 标签打印输出一些东西。

function Bing_wp_head_test_print(){
  echo '<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=0" />';
}
add_action( 'wp_head', 'Bing_wp_head_test_print' );

其它

该函数位于:wp-includes/plugin.php

do_action()(执行动作)
do_action() 用来执行动作钩子,它和 apply_filters() 的区别在于没有返回值,单纯的就是在特定的地方执行插件或者主题开发者挂载的函数,一般存在于某个特殊的节点或者事件上(比如开始加载主题模板的时候或者发布一篇文章的时候)。

用法

do_action( $tag, $arg... );

参数

$tag

(字符串)(必须)要执行的动作的名字。

$arg

(混合)(可选)额外的参数,会被传到调用的函数里,可以添加无限个,比如保存文章的时候触发 save_post 动作,就可以把保存的文章的 id 穿进去,让回调函数根据文章 id 进行操作。

返回值

None

例子

function func(){
  echo '测试';
}
add_action( 'test', 'func' );
do_action( 'test' );

屏幕打印:

测试

更多参考类似的 apply_filters():http://www.endskin.com/apply_filters/

其它

此函数位于:wp-includes/plugin.php

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn