插件开发文档

💡 云策文档标注

概述

Filters 是 WordPress 中两种 Hook 类型之一,用于在核心、插件和主题执行期间修改数据,与 Actions 相对应。它们以隔离方式工作,应返回修改后的值,避免副作用。

关键要点

  • Filters 是 Hooks 的一种,专注于数据修改,与 Actions 不同,应返回结果且无副作用。
  • 添加 Filter 需使用 add_filter() 函数,至少包含 hook_name 和 callback 参数,并可设置 priority 和 accepted_args。
  • 通过回调函数实现过滤逻辑,例如修改标题或添加 CSS 类,代码示例展示了具体应用。

代码示例

function wporg_filter_title( $title ) {
    return 'The ' . $title . ' was filtered';
}
add_filter( 'the_title', 'wporg_filter_title' );
function wporg_css_body_class( $classes ) {
    if ( ! is_admin() ) {
        $classes[] = 'wporg-is-awesome';
    }
    return $classes;
}
add_filter( 'body_class', 'wporg_css_body_class' );

📄 原文内容

Filters are one of the two types of Hooks.

They provide a way for functions to modify data during the execution of WordPress Core, plugins, and themes. They are the counterpart to Actions.

Unlike Actions, filters are meant to work in an isolated manner, and should never have side effects such as affecting global variables and output. Filters expect to have something returned back to them.

Add Filter

The process of adding a filter includes two steps.

First, you need to create a Callback function which will be called when the filter is run. Second, you need to add your Callback function to a hook which will perform the calling of the function.

You will use the add_filter() function, passing at least two parameters:

  1. string $hook_name which is the name of the filter you’re hooking to, and
  2. callable $callback the name of your callback function.

The example below will run when the the_title filter is executed.

function wporg_filter_title( $title ) {
	return 'The ' . $title . ' was filtered';
}
add_filter( 'the_title', 'wporg_filter_title' );

Lets say we have a post title, “Learning WordPress”, the above example will modify it to be “The Learning WordPress was filtered”.

You can refer to the Hooks chapter for a list of available hooks.

As you gain more experience, looking through WordPress Core source code will allow you to find the most appropriate hook.

Additional Parameters

add_filter() can accept two additional parameters, int $priority for the priority given to the callback function, and int $accepted_args for the number of arguments that will be passed to the callback function.

For detailed explanation of these parameters please read the article on Actions.

Example

To add a CSS class to the <body> tag when a certain condition is met:

function wporg_css_body_class( $classes ) {
	if ( ! is_admin() ) {
		$classes[] = 'wporg-is-awesome';
	}
	return $classes;
}
add_filter( 'body_class', 'wporg_css_body_class' );