最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

code - Beautify WordPress HTML output without any plugins

programmeradmin1浏览0评论

Is there a simple (and without plugin) way to clean up the WordPress output of HTML? With a beautiful indentation of the code? I don't understand why, but my HTML output isn't perfect and it makes me uncomfortable.

Is there a simple (and without plugin) way to clean up the WordPress output of HTML? With a beautiful indentation of the code? I don't understand why, but my HTML output isn't perfect and it makes me uncomfortable.

Share Improve this question edited Feb 11, 2017 at 18:48 shanebp 5,0836 gold badges27 silver badges40 bronze badges asked Feb 11, 2017 at 12:47 William OdeWilliam Ode 1232 silver badges11 bronze badges 2
  • You might be able to use ob_start() and ob_get_clean() to capture all the output before it's written. Next, you would just need a mechanism to indent nested tags. – jgraup Commented Feb 11, 2017 at 19:18
  • See: stackoverflow/a/12243304 – jgraup Commented Feb 11, 2017 at 19:28
Add a comment  | 

1 Answer 1

Reset to default 2

Great question, I asked it myself and here's what I came up with. You can just use this in a custom plugin or in 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);
发布评论

评论列表(0)

  1. 暂无评论