我在插件或主题中遇到过这种类型的代码,其中使用了apply_filter,但不一定有现有的filter 或add_filter
在这种情况下,如果使用 apply_filters 而不使用过滤器,则您必须在要运行它的地方再次调用该函数。例如,在主题的标题中。
以下是在header.php 中再次调用的函数中使用的应用过滤器示例
if ( ! function_exists( 'header_apply_filter_test' ) ) {
function header_apply_filter_test() {
$filter_this_content = "Example of content to filter";
ob_start();
echo $filter_this_content;
$output = ob_get_clean();
echo apply_filters( 'header_apply_filter_test', $output );//used here
}
}
现在在header.php 文件中,你必须调用这个函数,因为它没有被挂在任何地方。因此,在这种情况下,要在标题中显示输出,您可以像这样调用函数:
<?php header_apply_filter_test(); ?>
您也可以使用钩子编写此代码,它会做同样的事情,即在标题中显示输出。
add_filter('wp_head', 'header_apply_filter_test');
if ( ! function_exists( 'header_apply_filter_test' ) ) {
function header_apply_filter_test() {
$filter_this_content = "Example of content to filter";
ob_start();
echo $filter_this_content;
$output = ob_get_clean();
echo $output;
}
}
对于第二个选项,您仍然可以在其他任何地方使用 apply_filters 来调用回调函数 header_apply_filter_test(),因为过滤器现在存在。
所以在我看来,底线是一个用例,因为任何一种方法都有效!