无需任何插件即可美化WordPress的HTML输出

时间:2017-02-11 作者:William Ode

有没有一种简单(而且没有插件)的方法来清理HTML的WordPress输出?有一个漂亮的缩进代码?我不明白为什么,但我的HTML输出并不完美,这让我感到不舒服。

1 个回复
SO网友:Adam Genshaft

好问题,我自己问的,下面是我想到的。您可以在自定义插件或functions.php.

// turn on Output Buffering (hence *ob*)
ob_start();
// register a callback to run after Wordpress has outputed everything
add_action(\'shutdown\', function () { 
    // get the output buffer and store it to a variable
    $html = ob_get_clean();
    // setup the PHP native html beautifier called tidy
    // note that you need to have libtidy installed
    // but chances are that your server already have it
    $tidy = new \\tidy;
    $tidy->parseString($html, [
        \'indent\' => true,
        \'output-xhtml\' => true,
        \'wrap\' => 200
    ], \'utf8\');
    $tidy->cleanRepair();
    // output the beautified html
    echo $tidy;
    // Use 0 as third parameter to the add_action so you will
    // register the action as early as possible. Otherwise 
    //  Wordpress will flush the output buffer before you do...
}, 0);

相关推荐

快捷代码返回转义的HTML标记

为了把事情放在上下文中,我正在使用WordPress上的龙门架,它与木材和树枝捆绑在一起。我有这个密码,基本的,make-your-text-bold 短代码// Add Shortcode function bold_text_shortcode( $atts , $content = null ) { return \'<strong>\' . $content . \'</strong>\'; } add_shortcode( \'b\