Minifying CSS in a WordPress theme or plugin is an important step in optimizing a website and improving its overall performance. By minifying CSS, you can reduce the total file size of your theme or plugin, improving page loading times and reducing the amount of data that must be transferred over the internet. Minifying CSS involves removing unnecessary characters such as spaces, line breaks, and comments without changing the overall functionality of the code. This can help to decrease the download time of a website by as much as 50%, making it an important step in optimizing any WordPress website.

When minifying CSS in a WordPress theme or plugin, it is important to ensure that the changes do not cause any errors or break the functionality of the theme or plugin. This can be done by testing the code before and after minification to ensure that all features are working correctly. Additionally, it is important to maintain the original code for future reference, as the original code may be needed if an issue arises.

There are several tools available that can assist with minifying CSS in a WordPress theme or plugin. But we are going to use a simple function to minify CSS. I use this function for inline CSS in my WordPress themes or plugins.

We will name the function minify_css() with $css parameter/argument which will be used to pass the CSS for minification. There is not much to explain in the following function as you can see what the preg_replace() and str_replace() functions are replacing step by step.

function minify_css($css) {

  $css = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $css);
  $css = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $css);
  $css = str_replace(array('{ ', ' {'), '{', $css);
  $css = str_replace(array('} ', ' }'), '}', $css);
  $css = str_replace('; ', ';', $css);
  $css = str_replace(': ', ':', $css);
  $css = str_replace(', ', ',', $css);
  $css = str_replace(array('> ', ' >'), '>', $css);
  $css = str_replace(array('+ ', ' +'), '+', $css);
  $css = str_replace(array('~ ', ' ~'), '~', $css);
  $css = str_replace(';}', '}', $css);

  return $css;

}

Muhammad Zohaib

Web Developer specializing in WordPress to develop custom themes, plugins, troubleshooting technical issues and ensuring websites are optimized for search engines and meet accessibility standards. Currently working as Lead Developer at XeCreators.

Leave a Reply

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


The reCAPTCHA verification period has expired. Please reload the page.