Minify HTML files to a WordPress site without plugin

minify html wordpress

Among the best practices to be up when optimizing load time of pages of a website is regularly speaks of the "minification" HTML, CSS and JavaScript.

Behind this barbarous word hides a very simple technique: it is to compress a file up to reduce its weight. To do this, remove all code comments, line breaks and unnecessary spaces in the file.

For minify our files easily, there are several WordPress plugins like WP Minify or W3 Total Cache.

Yet with a few lines of code, it is possible to optimize the weight of our files without plugin. For example, to reduce the weight of HTML files from a WordPress theme, copy the following code in the functions.php file at the root of your theme:

  1. add_action('get_header', 'gkp_html_minify_start');
  2. function gkp_html_minify_start() {
  3. ob_start( 'gkp_html_minyfy_finish' );
  4. }
  5.  
  6. function gkp_html_minyfy_finish( $html ) {
  7.  
  8. // Suppression des commentaires HTML,
  9. // sauf les commentaires conditionnels pour IE
  10. $html = preg_replace('/<!--(?!s*(?:[if [^]]+]|!|>))(?:(?!-->).)*-->/s', '', $html);
  11.  
  12. // Suppression des espaces vides
  13. $html = str_replace(array("\r\n", "\r", "\n", "\t"), '', $html);
  14. while ( stristr($html, ' '))
  15. $html = str_replace(' ', ' ', $html);
  16.  
  17. return $html;
  18. }

Similar Article : 10 tips for choosing a WordPress plugin

Minify HTML files to a WordPress site without plugin Minify HTML files to a WordPress site without plugin Reviewed by Aqib Anjum on March 04, 2015 Rating: 5

4 comments:

  1. Hello I tried this script with wordpress. It seemed to work fine. However one thing I noticed is that all my pre and code tags stopped working. All code was with a scroll bar inline. No css styling help. When I disabled your script it all went back to normal

    ReplyDelete
    Replies
    1. Hi Daniel, then you Better use these two Plugin's : WP Minify or W3 Total Cache.

      Delete
  2. I was hoping to do it without a plugin. I thought maybe it had to do with the regular expression used but I really am bad at regular expressions.
    Thank you

    ReplyDelete
  3. Would it have something to do with a possible typo in this:
    "gkp_html_minyfy_finish"

    ReplyDelete

Powered by Blogger.