# 高级主题 #### 删除操作和过滤器 有时您想从另一个插件、主题甚至 WordPress Core 已注册的挂钩中删除回调函数。 要从挂钩中删除回调函数,您需要调用`remove_action()`或 `remove_filter()`,具体取决于回调函数是作为操作还是过滤器添加。 `remove_action()`传递给/ 的参数 必须与传递给/注册它的`remove_filter()`参数相同,否则删除将不起作用。`add_action()``add_filter()`
警报:要成功删除回调函数,您必须在注册回调函数后执行删除操作。执行顺序很重要。
#### 例子 假设我们希望通过删除不必要的功能来提高大型主题的性能。 让我们通过查看 来分析主题的代码`functions.php`。
```php function wporg_setup_slider() { // ... } add_action( 'template_redirect', 'wporg_setup_slider', 9 ); ``` 该`wporg_setup_slider`函数正在添加一个我们不需要的滑块,它可能会加载一个巨大的 CSS 文件,然后加载一个 JavaScript 初始化文件,该文件使用大小为 1MB 的自定义编写库。我们可以摆脱它。 `wporg_setup_slider`由于我们希望在注册(执行)回调函数后挂钩 WordPress,因此`functions.php`最好的机会就是`after_setup_theme`挂钩。
```php function wporg_disable_slider() { // Make sure all parameters match the add_action() call exactly. remove_action( 'template_redirect', 'wporg_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()`。 #### 确定当前钩子 有时您想要在多个钩子上运行一个操作或一个过滤器,但根据当前调用它的钩子而表现不同。 您可以使用 `current_action()`/`current_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()](https://developer.wordpress.org/reference/functions/did_action/)检查钩子运行了多少次。
```php function wporg_custom() { // If save_post has been run more than once, skip the rest of the code. if ( did_action( 'save_post' ) !== 1 ) { return; } // ... } add_action( 'save_post', 'wporg_custom' ); ``` #### 使用“all”Hook 进行调试 如果您希望在每个钩子上触发回调函数,则可以将其注册到该`all`钩子。有时,这在调试情况下很有用,可以帮助确定特定事件何时发生或页面何时崩溃。
```php function wporg_debug() { echo '

' . current_action() . '

'; } add_action( 'all', 'wporg_debug' ); ```