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
1 Answer
Reset to default 2Great 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);