高级主题
删除操作和过滤器
有时您想从另一个插件、主题甚至 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()
。
确定当前钩子
有时你想在多个挂钩上运行一个 Action 或一个 Filter,但根据当前调用它的人的不同表现不同。
您可以使用 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”Hook 进行调试
如果你想要一个回调函数在每个钩子上触发,你可以将它注册到钩子上all
。有时这在调试情况下很有用,可帮助确定特定事件何时发生或页面何时崩溃。
function wporg_debug() {
echo '<p>' . current_action() . '</p>';
}
add_action( 'all', 'wporg_debug' );