高级用法

删除动作和筛选器

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

要从钩子中删除回调函数,需要调用remove_action()remove_filter(),这取决于回调函数是作为动作还是过滤器添加的。

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

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

 

实例

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

让我们通过研究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()确定当前动作/过滤器。

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' );