删除操作和过滤器

有时你想从另一个插件、主题甚至WordPress Core已经注册的钩子中删除回调函数。

要从钩子中删除回调函数,您需要调用 remove_action()或remove_filter() ,具体取决于回调函数是作为 Action 还是 Filter 添加的。

传递给remove_action() / remove_filter()的参数必须与传递给注册它的add_action() /add_filter() 的参数相同,否则删除将不起作用。

警报:若要成功删除回调函数,必须在注册回调函数后执行删除。执行顺序很重要。
 

假设我们想通过删除不必要的功能来提高大型主题的性能。

让我们通过查看来分析主题的functions.php代码。

function wporg_setup_slider() {
	// ...
}
add_action( 'template_redirect', 'wporg_setup_slider', 9 );

wporg_setup_slider函数正在添加一个我们不需要的滑块,它可能加载一个巨大的 CSS 文件,然后加载一个 JavaScript 初始化文件,该文件使用大小为 1MB 的自定义编写库。

由于我们想在回调函数wporg_setup_slider注册(functions.php执行)后挂接到WordPress,我们最好的机会是after_setup_theme钩子。

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()来确定当前action / filter。

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() 运行了多少次。

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”钩子进行调试

如果您希望在每个钩子上触发回调函数,可以将其注册到all钩子中。有时,这在调试情况下很有用,以帮助确定特定事件发生的时间或页面崩溃的时间。

function wporg_debug() {
	echo '<p>' . current_action() . '</p>';
}
add_action( 'all', 'wporg_debug' );