移除操作和过滤器
有时您想从另一个插件、主题甚至 WordPress 核心注册的操作钩中移除回调函数。
要从钩中移除回调函数,您需要根据该回调函数是作为操作还是过滤器添加的,调用 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 回调函数注册(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' );