---
title: "Minify HTML, JS và CSS trong WordPress không cần plugin"
author: "Trung Hiếu"
date: "2014-06-04"
lastmod: "2022-06-19"
url: "https://wpcanban.com/wordpress/thu-thuat-wordpress/minify-html-javascript-va-css-ma-khong-can-plugin.html"
---

# Minify HTML, JS và CSS trong WordPress không cần plugin

Minify HTML, JavaScript và CSS trong WordPress mà không cần plugin.

![minify-html-javascript-css-trong-wordpress-khong-can-plugin](https://wpcanban.com/wp-content/uploads/2014/06/minify-css-html-js-trong-wordpress-khong-can-plugin.png)

Sử dụng quá nhiều plugin trên blog/ website [\*WordPress\*](https://wpcanban.com/category/wordpress) không bao giờ là một ý tưởng tốt. Bởi vì chúng ta đều biết rằng các hacker có thể dễ dàng tấn công blog/ website *WordPress* của bạn thông qua việc khai thác lỗ hổng từ plugin. Tại sao không cố gắng để giảm bớt sự phụ thuộc vào các plugin? Một số tính năng hữu ích có thể được bổ sung dễ dàng bằng cách thêm code snippets vào file *function.php* của theme mà bạn đang sử dụng. Bao gồm cả thủ thuật độc đáo sau đây để minify HTML, CSS và JavaScript.

Tham khảo thêm:

- [\*Top 4 plugins minify dữ liệu tốt nhất cho WordPress\*](https://wpcanban.com/wordpress/wordpress-plugins/top-4-plugins-minify-du-lieu-tot-nhat-cho-blog-wordpress.html)
- *[Làm thế nào để giảm bớt HTTP requests cho WordPress?](https://wpcanban.com/wordpress/thu-thuat-wordpress/lam-the-nao-de-giam-bot-http-requests-cho-wordpress.html)*

Giảm bớt hay minify HTML, JavaScript và CSS về cơ bản là giảm kích thước của các tập tin. Từ đó, chúng sẽ nhỏ hơn, nhẹ hơn và load nhanh hơn, giúp cải thiện tốc độ hiển thị nội dung trên trình duyệt web. Việc minify dữ liệu về cơ bản là khá đơn giản. Bạn chỉ cần tìm cách loại bỏ các vùng không gian trống, tham số và comments của JavaScript, CSS, HTML là được. Chức năng minify có thể được tìm thấy trong một số plugin như *WP-Minify *hay *Autoptimize*. Nếu đang sử dụng plugin *W3 Total Cache*, bạn cũng chỉ cần vài thao tác đơn giản để kích hoạt tính năng này. Nhưng chúng ta đang cố gắng hạn chế sự phụ thuộc vào plugin. Vậy nên, điều chúng ta cần là một phương pháp để thay thế.

## Minify HTML, JavaScript và CSS trong WordPress

Trên thực tế, các bạn có thể làm điều này một cách dễ dàng mà không cần đến plugin. Tất cả những gì bạn cần làm là copy và paste đoạn code sau đây vào file *functions.php* của theme mà bạn đang sử dụng.

```
class WP_HTML_Compression
{
	// Settings
	protected $compress_css = true;
	protected $compress_js = true;
	protected $info_comment = true;
	protected $remove_comments = true;

	// Variables
	protected $html;
	public function __construct($html)
	{
		if (!empty($html))
		{
			$this->parseHTML($html);
		}
	}
	public function __toString()
	{
		return $this->html;
	}
	protected function 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 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;
		// Variable reused for output
		$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 ($content == '<!--wp-html-compression no compression-->')
				{
					$overriding = !$overriding;

					// Don't print the comment
					continue;
				}
				else if ($this->remove_comments)
				{
					if (!$overriding && $raw_tag != 'textarea')
					{
						// Remove any HTML comments, except MSIE conditional comments
						$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;

						// Remove any empty attributes, except:
						// action, alt, content, src
						$content = preg_replace('/(\s+)(\w++(?<!\baction|\balt|\bcontent|\bsrc)="")/', '$1', $content);

						// Remove any space before the end of self-closing XHTML tags
						// JavaScript excluded
						$content = str_replace(' />', '/>', $content);
					}
				}
			}

			if ($strip)
			{
				$content = $this->removeWhiteSpace($content);
			}

			$html .= $content;
		}

		return $html;
	}

	public function parseHTML($html)
	{
		$this->html = $this->minifyHTML($html);

		if ($this->info_comment)
		{
			$this->html .= "\n" . $this->bottomComment($html, $this->html);
		}
	}

	protected function 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 wp_html_compression_finish($html)
{
	return new WP_HTML_Compression($html);
}

function wp_html_compression_start()
{
	ob_start('wp_html_compression_finish');
}
add_action('get_header', 'wp_html_compression_start');
```

Nếu code bị lỗi, các bạn có thể download file text [tại đây](http://dvslabs.googlecode.com/files/minifier-script-en.txt) về máy tính để xem chi tiết.

Để kiểm tra xem liệu các chức năng minify có thực sự hoạt động hay không, các bạn chỉ cần view source (Ctrl + U) của blog/ website. Ở cuối mã nguồn, các bạn sẽ thấy thông báo trông như thế này:

> 

<!–-HTML compressed, size saved …%. From …bytes, now …bytes-–>

Đơn giản vậy thôi. Chúc các bạn thành công!

*Nếu bạn thích bài viết này, hãy subscribe blog của tôi để thường xuyên cập nhật những bài viết hay nhất, mới nhất qua email nhé. Cảm ơn rất nhiều.* :)
