Filter template_include
, 使用输出缓冲捕获渲染的文件内容,并DOMDocument
来改变它。
未经测试的示例:
add_filter( \'template_include\', function( $template ) {
// Bail out early.
if ( \'the-file-you-want-to-filter\' !== $template )
return $template;
get_header();
ob_start();
include $template;
$content = ob_get_clean();
// See user notes on http://php.net/manual/en/domdocument.loadhtml.php
$doc = new DOMDocument();
$doc->loadHTML( \'<?xml encoding="UTF-8">\' . $content );
// dirty fix
foreach ($doc->childNodes as $item)
if ($item->nodeType == XML_PI_NODE)
$doc->removeChild($item); // remove hack
$doc->encoding = \'UTF-8\'; // insert proper
/**
* Edit the file content here.
*/
echo $doc->saveHTML();
get_footer();
return FALSE;
});