Skip to content

Instantly share code, notes, and snippets.

@makeitaboldmove
Last active September 16, 2018 19:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save makeitaboldmove/97dc252ce0bc0535305cfcb751d3c4ef to your computer and use it in GitHub Desktop.
Save makeitaboldmove/97dc252ce0bc0535305cfcb751d3c4ef to your computer and use it in GitHub Desktop.
How to minify HTML using WordPress functions.php
<?php
/*********
*********
Minify
*********
*********/
class WP_Minify{
protected $compress_css = true;
protected $compress_js = false;
protected $img_to_base64 = true;
protected $remove_comments = false;
protected $html;
public function __construct($html){
if(!empty($html)){
$this->parseHTML($html);
}
}
public function __toString(){
return $this->html;
}
protected function minifyHTML($html){
$pattern = '/<(?<script>script).*?<\/script\s*>|<(?<style>style).*?<\/style\s*>|<!(?<comment>--).*?-->|<(?<tag>[\/\w.:-]*)(?:".*?"|\'.*?\'|[^\'">]+)*>|(?<text>((<[^!\/\w.:-])?[^<]*)+)|/si';
preg_match_all($pattern, $html, $matches, PREG_SET_ORDER);
$overriding = false;
$raw_tag = false;
$html = '';
foreach($matches as $token){
$tag = isset($token['tag']) ? strtolower($token['tag']) : null;
$content = $token[0];
if(is_null($tag)){
if(!empty($token['script'])){
$strip = $this->compress_js;
} else if(!empty($token['style'])){
$strip = $this->compress_css;
} else if($this->remove_comments){
if(!$overriding && $raw_tag != 'textarea'){
$content = preg_replace('/<!--(?!\s*(?:\[if [^\]]+]|<!|>))(?:(?!-->).)*-->/s', '', $content);
}
}
} else{
if($tag == 'pre' || $tag == 'textarea' || $tag == 'script'){
$raw_tag = $tag;
} else if($tag == '/pre' || $tag == '/textarea' || $tag == '/script'){
$raw_tag = false;
} else if($tag == 'img' && $this->img_to_base64){
$content = preg_replace_callback('/(<img\s+src=["\'])([^"\']+)(["\']\s+[^>]+>)/', function($matches){
$file = file_get_contents($matches[2]);
$file_info = new finfo(FILEINFO_MIME_TYPE);
$mime = $file_info->buffer($file);
$data = base64_encode($file);
return $matches[1] . "data:$mime;base64,$data" . $matches[3];
}, $content);
} else{
if($raw_tag || $overriding){
$strip = false;
} else{
$strip = true;
$content = preg_replace('/(\s+)(\w++(?<!\baction|\balt|\bcontent|\bsrc)="")/', '$1', $content);
$content = str_replace(['/>', ' />', ' >'], '>', $content);
}
}
}
if($strip){
$content = $this->removeWhiteSpace($content);
}
$html .= $content;
}
return $html;
}
public function parseHTML($html){
$this->html = $this->minifyHTML($html);
}
protected function removeWhiteSpace($str){
$str = str_replace([' ', '&nbsp;'], ' ', $str);
$str = str_replace(["\t", "\n", "\r"], '', $str);
return $str;
}
}
add_action('get_header', function(){
ob_start(function($html){
return new WP_Minify($html);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment