Skip to content

Instantly share code, notes, and snippets.

@yratof
Created March 6, 2018 12:30
Show Gist options
  • Save yratof/8047e39ca807af61d5f7b21582d69039 to your computer and use it in GitHub Desktop.
Save yratof/8047e39ca807af61d5f7b21582d69039 to your computer and use it in GitHub Desktop.
Minify wordpress
<?php
/**
* Minify HTML
*/
class drivkraft_compression {
/* Run compression */
static function run() {
add_action( 'get_header', __CLASS__ . '::drivkraft_html_minify_start' );
}
/* Capture HTML */
static function drivkraft_html_minify_start() {
ob_start( 'drivkraft_compression::drivkraft_html_minyfy_finish' );
}
/* Remove all extra white space from all HTML */
static function drivkraft_html_minyfy_finish( $html ) {
$html = preg_replace( '/(?:(?:\/\*(?:[^*]|(?:\*+[^*\/]))*\*+\/)|(?:(?<!\:|\\\|\')\/\/.*))/', '', $html);
/* Remove \r (return) from $html */
$html = preg_replace("/<\/html>\s+/", "</html>", $html);
/* Removes whitespace */
$html = preg_replace("/^\s+/m", "", ( (string) $html ));
/* Remove all aps and new lines */
$html = str_replace( [ PHP_EOL ], '', $html );
/* Bring back all the HTML in one line */
return $html;
}
}
drivkraft_compression::run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment