通知短信+运营短信,5秒速达,支持群发助手一键发送🚀高效触达和通知客户 广告
## 删除操作和过滤器 有时您想要从另一个插件,主题甚至WordPress Core已注册的钩子中删除回调函数。 要从挂钩中删除回调函数,您需要调用remove_action()或remove_filter(),这取决于回调函数是作为Action还是Filter来添加。 传递给remove_action()/ remove_filter()的参数应与传递给注册它的add_action()/ add_filter()的参数相同。 >[warning] 警报:要成功删除回调函数,您必须在注册回调函数后执行删除。 执行顺序很重要。 示例 我们希望通过删除不必要的功能来改善大型主题的性能。 我们通过查看functions.php来分析主题的代码。 ``` <?php function my_theme_setup_slider() { // ... } add_action('template_redirect', 'my_theme_setup_slider', 9); ``` my_theme_setup_slider函数正在添加一个我们不需要的滑块,这可能会加载一个巨大的CSS文件,然后是一个JavaScript初始化文件,它使用大小为1MB的自定义书写库。 我们可以摆脱这一点。 因为我们希望在注册my_theme_setup_slider回调函数(functions.php执行)之后挂接到WordPress中,所以最好的机会是after_setup_theme钩子。 ``` <?php function wporg_disable_slider() { // make sure all parameters match the add_action() call exactly remove_action('template_redirect', 'my_theme_setup_slider', 9); } // make sure we call remove_action() after add_action() has been called add_action('after_setup_theme', 'wporg_disable_slider'); ``` ##删除所有回调 您也可以使用remove_all_actions()/ remove_all_filters()来删除与钩子相关联的所有回调函数。 确定当前挂钩 有时您想要在多个钩子上运行一个Action或Filter,但是根据当前调用它的行为有所不同。 您可以使用current_action()/ current_filter()来确定当前的Action / Filter。 ``` <?php function wporg_modify_content($content) { switch (current_filter()) { case 'the_content': // do something break; case 'the_excerpt': // do something break; } return $content; } add_filter('the_content', 'wporg_modify_content'); add_filter('the_excerpt', 'wporg_modify_content'); ``` ## 检查一个钩子有多少次运行 一些钩子在执行过程中被多次调用,但您可能只希望您的回调函数运行一次。 在这种情况下,您可以使用did_action()检查钩子运行的次数。 ``` <?php function wporg_custom() { if (did_action('save_post') !== 1) { return; } // ... } add_action('save_post', 'wporg_custom'); ``` ## 用“all”钩子调试 如果你想要一个回调函数在每个钩子上触发,你可以注册到所有的钩子。 有时,这在调试情况有助于确定特定事件何时发生或页面崩溃时有用。 ``` <?php function wporg_debug() { echo '<p>' . current_action() . '</p>'; } add_action('all', 'wporg_debug'); ```