How to Minify HTML in WordPress Without a Plugin

CatchMyPage > Blog > Uncategorized > How to Minify HTML in WordPress Without a Plugin
Share on facebook
Facebook
Share on google
Google+
Share on twitter
Twitter
Share on linkedin
LinkedIn

Minification is a simple concept that is often recommended as a step towards speeding up your website. But the reality is, it frustrates many site owners no end when they attempt to minify their files and end up breaking their site.

Minification often requires a lot of experimentation. While there are many solutions available, how they behave will vary from site to site depending on what theme and plugins you are using.

In this post, we’ll explore what minification is, its benefits, and some of the more popular minification solutions available – both manual and plugins – to help point you to the right solution for your site.

What is HTML Minification?

When you minify HTML it removes the unnecessary characters and lines in the source code. Indentation, comments, empty lines, etc. are not required in HTML. They just make the file easier to read. Cutting out all this unnecessary stuff can shave down your file size considerably. When you minify HTML code on your website, the server will send a much smaller page to the client making your website load quicker.

WordPress creates pages on demand by executing PHP code to put together the HTML version of your site and querying your database to get the content to insert into that HTML. There is no physical file that we can download and minify ourselves, so we will need to use a bit of PHP code inside the functions.php file of your theme. This code will compress the output HTML before being sent to your visitors. Below are two screenshots that show a webpage before and after HTML Minification.

 

Before Minification
After Minification

 

 

 

 

 

 

Step 1: Create a Child Theme

Before we edit the functions.php file, it’s always best to create a child theme. Using a child theme will allow you to revert back to the parent theme if there are problems. Also, any changes you make will not be deleted if your parent theme gets updated.

If you prefer not to create a child theme or you do not feel comfortable doing this on your own, there is a great lightweight plugin you can use called Code Snippets. Code Snippets is an easy, clean and simple way to add code snippets to your site. It removes the need to add custom snippets to your theme’s functions.php file.

Step 2: Edit your Child Theme functions.php File

There are 2 different ways we can edit the functions.php file in your child theme.

Inside WordPress Control Panel

While you are logged into WordPress you can access and edit the functions.php file of your theme by going to Appearance > Editor and selecting Theme Functions on the right hand side of the page.

Edit the File Directly in cPanel

Log into your cPanel File Manager. Go to the public_html/wp-content/themes/ and choose the folder of your current theme or child theme if you have created one. The functions.php file will be inside your theme folder.

Copy and paste the code below inside your functions.php file and save.

class FLHM_HTML_Compression
{
protected $flhm_compress_css = true;
protected $flhm_compress_js = true;
protected $flhm_info_comment = true;
protected $flhm_remove_comments = true;
protected $html;
public function __construct($html)
{
if (!empty($html))
{
$this->flhm_parseHTML($html);
}
}
public function __toString()
{
return $this->html;
}
protected function flhm_bottomComment($raw, $compressed)
{
$raw = strlen($raw);
$compressed = strlen($compressed);
$savings = ($raw-$compressed) / $raw * 100;
$savings = round($savings, 2);
return '<!--HTML compressed, size saved '.$savings.'%. From '.$raw.' bytes, now '.$compressed.' bytes-->';
}
protected function flhm_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->flhm_compress_js;
}
else if ( !empty($token['style']) )
{
$strip = $this->flhm_compress_css;
}
else if ($content == '<!--wp-html-compression no compression-->')
{
$overriding = !$overriding;
continue;
}
else if ($this->flhm_remove_comments)
{
if (!$overriding && $raw_tag != 'textarea')
{
$content = preg_replace('/<!--(?!\s*(?:\[if [^\]]+]|<!|>))(?:(?!-->).)*-->/s', '', $content);
}
}
}
else
{
if ($tag == 'pre' || $tag == 'textarea')
{
$raw_tag = $tag;
}
else if ($tag == '/pre' || $tag == '/textarea')
{
$raw_tag = false;
}
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->flhm_removeWhiteSpace($content);
}
$html .= $content;
}
return $html;
}
public function flhm_parseHTML($html)
{
$this->html = $this->flhm_minifyHTML($html);
if ($this->flhm_info_comment)
{
$this->html .= "\n" . $this->flhm_bottomComment($html, $this->html);
}
}
protected function flhm_removeWhiteSpace($str)
{
$str = str_replace("\t", ' ', $str);
$str = str_replace("\n",  '', $str);
$str = str_replace("\r",  '', $str);
while (stristr($str, '  '))
{
$str = str_replace('  ', ' ', $str);
}  
return $str;
}
}
function flhm_wp_html_compression_finish($html)
{
return new FLHM_HTML_Compression($html);
}
function flhm_wp_html_compression_start()
{
ob_start('flhm_wp_html_compression_finish');
}
add_action('get_header', 'flhm_wp_html_compression_start');

Step 3: Make Sure Everything is Working

After you have added the code, you can check to see if the HTML is being minified on Google Chrome by right clicking the page and selecting “View page source.” If everything is working correctly, it should look like the example picture I gave at the top of this page.

I highly recommend you check all aspects of your website after you add this code. Check and make sure all plugins and theme functionality is working properly.

If you run into any issues, be sure to let me know in the comments below. I will do my best to try and help walk you through it.

Share on facebook
Facebook
Share on google
Google+
Share on twitter
Twitter
Share on linkedin
LinkedIn

Other Popular Articles

Leave a Comment

Your email address will not be published. Required fields are marked *

Join CatchMyPage Community

Popular Resources

Start a Blog

Step by step guide on how to start a blog.

Make a Website

Beginners guide on how to make a website.

Performance

Compare the best caching plugins.

Security

Compare the best security plugins.

Recent Posts​

Recommended Host

DreamHost

Recommended Theme

Check List

About CatchMyPage

CatchMyPage is a tech blog and we cover all the aspects of digital marketing. You will find free content around Blogging, SEO, Affiliate Marketing, WordPress, Web-hosting and making money online. 

catchmypage-logo    2020 CatchMyPage.
Hosted at HostGator & CDN by MaxCDN | Built on ASTRA Themes.

Scroll to Top