函数文档

remove_filter()

💡 云策文档标注

概述

remove_filter() 函数用于从指定的过滤器钩子中移除一个回调函数,常用于替换默认功能或动态调整钩子行为。移除时需确保回调函数和优先级与添加时匹配,否则可能失败且无警告。

关键要点

  • 核心功能:从过滤器钩子中移除回调函数,支持无条件调用以尝试移除可能不存在的回调。
  • 参数要求:$hook_name(钩子名称)和$callback(回调函数)为必需,$priority(优先级)可选,默认值为10,必须与添加时一致才能成功移除。
  • 返回值:返回布尔值,表示函数在移除前是否存在。
  • 应用场景:适用于移除默认过滤器(如wpautop)、批量移除多个钩子中的回调,或处理类中的过滤器移除。

代码示例

remove_filter( 'the_content', 'wpautop' );
foreach ( array( 'the_content', 'the_title', 'comment_text' ) as $hook )
    remove_filter( $hook, 'capital_P_dangit' );
global $my_class;
remove_filter( 'the_content', array($my_class, 'class_filter_function') );

注意事项

  • 移除过滤器必须在添加之后进行,否则无法成功;优先级需精确匹配添加时的值。
  • 对于类中的过滤器,需通过全局变量或实例访问类方法作为回调。
  • 函数失败时不会产生警告,开发者需自行处理返回值以确认移除状态。

📄 原文内容

Removes a callback function from a filter hook.

Description

This can be used to remove default functions attached to a specific filter hook and possibly replace them with a substitute.

To remove a hook, the $callback and $priority arguments must match when the hook was added. This goes for both filters and actions. No warning will be given on removal failure.

Parameters

$hook_namestringrequired
The filter hook to which the function to be removed is hooked.
$callbackcallable|string|arrayrequired
The callback to be removed from running when the filter is applied.
This function can be called unconditionally to speculatively remove a callback that may or may not exist.
$priorityintoptional
The exact priority used when adding the original filter callback.

Default:10

Return

bool Whether the function existed before it was removed.

Source

function remove_filter( $hook_name, $callback, $priority = 10 ) {
	global $wp_filter;

	$r = false;

	if ( isset( $wp_filter[ $hook_name ] ) ) {
		$r = $wp_filter[ $hook_name ]->remove_filter( $hook_name, $callback, $priority );

		if ( ! $wp_filter[ $hook_name ]->callbacks ) {
			unset( $wp_filter[ $hook_name ] );
		}
	}

	return $r;
}

Changelog

Version Description
1.2.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Example

    remove_filter( 'the_content', 'wpautop' );
    foreach ( array( 'the_content', 'the_title', 'comment_text' ) as $hook )
        remove_filter( $hook, 'capital_P_dangit' );

    If a filter has been added from within a class, for example by a plugin, removing it will require accessing the class variable.

    global $my_class;
    remove_filter( 'the_content', array($my_class, 'class_filter_function') );

    It is also worth noting that you may need to prioritise the removal of the filter to a hook that occurs after the filter is added. You cannot successfully remove the filter before it has been added.