WordPress 没有“最终输出”过滤器,但您可以组合一个。下面的示例位于我为项目创建的"Must Use" 插件中。
注意:我没有测试过任何可能使用“关闭”操作的插件。
插件通过遍历所有打开的缓冲区级别、关闭它们并捕获它们的输出来工作。然后它触发“final_output”过滤器,回显过滤后的内容。
遗憾的是,WordPress 执行几乎完全相同的过程(关闭打开的缓冲区),但实际上并没有捕获缓冲区进行过滤(只是刷新它),因此其他“关闭”操作将无法访问它。因此,以下操作的优先级高于 WordPress。
wp-content/mu-plugins/buffer.php
<?php
/**
* Output Buffering
*
* Buffers the entire WP process, capturing the final output for manipulation.
*/
ob_start();
add_action('shutdown', function() {
$final = '';
// We'll need to get the number of ob levels we're in, so that we can iterate over each, collecting
// that buffer's output into the final output.
$levels = ob_get_level();
for ($i = 0; $i < $levels; $i++) {
$final .= ob_get_clean();
}
// Apply any filters to the final output
echo apply_filters('final_output', $final);
}, 0);
挂钩到 final_output 过滤器的示例:
<?php
add_filter('final_output', function($output) {
return str_replace('foo', 'bar', $output);
});
编辑:
此代码使用匿名函数,仅在 PHP 5.3 或更高版本中受支持。如果您正在使用 PHP 5.2 或更早版本运行网站,那么您就是在伤害自己。 PHP 5.2 于 2006 年发布,尽管 Wordpress(edit: in WP version )仍然支持它,但你不应该使用它。