前言
WordPress中Hooks是一个很强大的功能,Action 和 Filter Hooks不管是在插件还是主题的开发中,我们经常看到这玩意,之前也是一直让我摸不着头脑。
Hooks分为两大类:Action和Filter。
本文将讨论他们的区别以及基础概念。
Action Hooks
Action Hook可以让我们在Wordpress运行时,发生不同的事件的时候运行我们自己想要的代码。
示例代码如下:
<?php function my_theme_styles(){ wp_enqueue_style('main-css',get_stylesheet_uri()) add_action('wp_enqueue_scripts','my_theme_styles')//插入js脚本的时候,插入我们想要的代码。 } ?>
Filter Hooks
Filter Hooks是在修改数据保存时或者修改数据如何显示时触发。
示例代码:
<?php function my_read_more_link($excerpt){ return $excerpt. '<a href="'.get_permalink().'"> Read More</a>'; } add_filter('get_the_excerpt','my_read_more_link',10);//添加 Filter Hooks ?>
Action 和 Filter相同点
Hooks都存放在主题的function.php文件中,或者存放在插件之中,不存在于模板文件中。