WordPress 具有强大的过滤器支持,可以获取各种特定的内容并在输出之前对其进行修改。与 the_content
过滤器类似,它允许您在帖子输出到屏幕之前访问帖子的标记。
我正在尝试找到一个包罗万象的过滤器,它可以让我在输出之前完整修改最终标记。
我已经多次浏览了过滤器列表,但没有任何结果: https://codex.wordpress.org/Plugin_API/Filter_Reference
有人知道吗?
最佳答案
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);
Hook 到 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(编辑:WP 版本 < 5.2)仍然支持它,但您不应该使用它。
关于WordPress 过滤器修改最终的 html 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/772510/