高级主题
删除操作和过滤器
有时您想从另一个插件、主题甚至 WordPress Core 已注册的挂钩中删除回调函数。
要从挂钩中删除回调函数,您需要调用remove_action()
或 remove_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
由于我们希望在注册(执行)回调函数后挂钩 WordPress,因此functions.php
最好的机会就是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”Hook 进行调试
如果您希望在每个钩子上触发回调函数,则可以将其注册到该all
钩子。有时,这在调试情况下很有用,可以帮助确定特定事件何时发生或页面何时崩溃。
function wporg_debug() {
echo '<p>' . current_action() . '</p>';
}
add_action( 'all', 'wporg_debug' );
无评论