WordPress函数apply_filters()调用链接到特定过滤器挂钩函数

WordPress函数apply_filters()调用链接到特定过滤器挂钩函数

WordPress函数apply_filters()调用链接到特定过滤器挂钩函数

  在 WordPress CMS内容管理系统中,apply_filters()一个内置函数,是 WordPress 的核心函数,用于在 WordPress 中应用过滤器挂钩。它用于通过过滤器挂钩传递数据并在需要时对其进行修改。

  推荐:[最新版]Swift Performance性能插件WordPress优化插件

apply_filters()函数基本语法

描述

  调用已链接到特定过滤器挂钩的所有函数

用法

// Define the filter callback function.
function example_callback( $string, $arg1, $arg2 ) {
    // (maybe) modify $string.
    return $string;
}

// Attach the 'example_callback' function to 'example_filter'.
add_filter( 'example_filter', 'example_callback', 10, 3 );

// Apply the filters by calling 'apply_filters'.
$value = apply_filters( 'example_filter', 'filter me', $arg1, $arg2 );
  • $hook_name (string):过滤器挂钩的名称。
  • $value (mixed):要过滤的值。
  • $args (mixed):传递给回调函数的附加参数

  推荐:WordPress函数get_the_terms()检索帖子附加的分类术语

apply_filters()函数

  apply_filters() 通过过滤器钩子传递数据,是 WordPress 编程的重要组成部分。(源文件可参考这里

function apply_filters( $hook_name, $value, ...$args ) {
	global $wp_filter, $wp_filters, $wp_current_filter;

	if ( ! isset( $wp_filters[ $hook_name ] ) ) {
		$wp_filters[ $hook_name ] = 1;
	} else {
		++$wp_filters[ $hook_name ];
	}

	// Do 'all' actions first.
	if ( isset( $wp_filter['all'] ) ) {
		$wp_current_filter[] = $hook_name;

		$all_args = func_get_args(); // phpcs:ignore PHPCompatibility.FunctionUse.ArgumentFunctionsReportCurrentValue.NeedsInspection
		_wp_call_all_hook( $all_args );
	}

	if ( ! isset( $wp_filter[ $hook_name ] ) ) {
		if ( isset( $wp_filter['all'] ) ) {
			array_pop( $wp_current_filter );
		}

		return $value;
	}

	if ( ! isset( $wp_filter['all'] ) ) {
		$wp_current_filter[] = $hook_name;
	}

	// Pass the value to WP_Hook.
	array_unshift( $args, $value );

	$filtered = $wp_filter[ $hook_name ]->apply_filters( $value, $args );

	array_pop( $wp_current_filter );

	return $filtered;
}

  推荐:WordPress函数email_exists()确定给定的电子邮件是否存在

如何使用apply_filters()

  过滤后输出,此代码将过滤器应用于$value,然后回显结果。

echo apply_filters( $tag, $value );

  被过滤,此代码将过滤器应用于$value,然后将结果分配给$myvar。

$myvar = apply_filters( $tag, $value );

  附加过滤器参数,此代码将过滤器应用于$value,并使用$param和$otherparam作为附加参数,然后将结果分配给$myvar。

$myvar = apply_filters( $tag, $value, $param, $otherparam );

  自定义标题过滤器,此代码将“the_title”过滤器应用于“My Custom Title™”,然后将结果分配给$my_custom_title。

$my_custom_title = apply_filters('the_title', ' My Custom Title (tm) ');

  指定参数数量,此代码将“example_callback”附加到“example_filter”,优先级为10,接受的参数为3。这可以防止诸如“Missing argument 2 for example_callback()”之类的错误。

add_filter( 'example_filter', 'example_callback', 10, 3 );

  推荐:WP Speed of Light插件使用教程WordPress速度优化插件

  推荐:WordPress函数使用手册

5/5 - (1 vote)

Claude、Netflix、Midjourney、ChatGPT Plus、PS、Disney、Youtube、Office 365、多邻国Plus账号购买,ChatGPT API购买,优惠码XDBK,用户购买的时候输入优惠码可以打95折

Chatgpt-Plus注册购买共享账号
滚动至顶部