Combine+Minify styles of parent theme and add as inline-style in wordpress


In a recent project, one of my tasks was to optimize and minify the styles included by the child-theme by combining and minify the styles of the parent theme into one file or include as custom inline style.

While working on the task, I ended up reading multiple resources to and writing the function below.

The function first fetches all the styles that are being included on page, and then for the handles belonging to the parent theme, the script then concatenates the scripts and then minifies by using preg_replace().
The generate combined CSS is stored in a database table and updated every 24 hours(triggered on page load).

It then de-registers the style handles we have combined and includes the custom style as an inline style.

This is the very first version of the function and suggestions/upgrades/ideas are welcome
(https://gist.github.com/aadilprabhakar/aef3fff9f8dbe897ca449479bb9cd2e3)

function parent_style_cache() {

global $wp_styles, $wpdb;

$updateFlag = 0;
$returnCss = null;

/**
* Check if our table exists else create
*/
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );

$table_name = $wpdb->prefix . "theme-cache";
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
time varchar(25) NOT NULL,
name varchar(25) NOT NULL,
text LONGTEXT NOT NULL,
PRIMARY KEY (id)
);";
dbDelta( $sql );

/**
* Check for latest styles
*/
$now = date('YmdHis');
$result = $wpdb->get_row("SELECT `time`,`text` FROM $table_name WHERE `name` = 'parent_styles' LIMIT 1;");
$diff = $now - ($result->time);

// print "<!-- Now is $now and last update was at $result->time and difference is ". $diff . "-->";

if($result){
if($now - $result-&gt;time &gt; 86400) {
$updateFlag = 1;
} else {
$returnCss = stripslashes( $result-&gt;text );
}
}

// print "<!-- UPDATE FLAG IS " . $updateFlag . "-->";

/**
* If updateFlag == 1, update the styles in database
*/
$wp_styles-&gt;all_deps($wp_styles-&gt;queue);

$handles = $wp_styles-&gt;to_do;
$deregHandle = [];
$css_code = '';

foreach ($handles as $handle) {
$src = strtok($wp_styles-&gt;registered[$handle]-&gt;src, '?');

if (strpos($src, 'http') !== false) {
$site_url = site_url();

if (strpos($src, $site_url) !== false) {
$css_file_path = str_replace($site_url, '', $src);
} else {
$css_file_path = $src;
}

$css_file_path = ltrim($css_file_path, '/');
} else {
$css_file_path = ltrim($src, '/');
}

if (strpos($css_file_path, '/parent-theme-domain/') !== false) {
$deregHandle[] = $handle;

// Combine the CSS if UPDATE FLAG is set
if( $updateFlag === 1 ) { $css_code .= file_get_contents($css_file_path); }
}

if($css_code !== "" &amp;&amp; $updateFlag === 1){
// Minify the combined CSS
$css_code = preg_replace('!/\*.*?\*/!s', '', $css_code);
$css_code = preg_replace('/\n\s*\n/', "\n", $css_code);
$css_code = str_replace('; ',';',str_replace(' }','}',str_replace('{ ','{',str_replace(array("\r\n","\r","\n","\t",' ',' ',' '),"",preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!','',$css_code)))));
$css_code = str_replace('"', "'", $css_code);
}
}

/**
* Lets update the database cache
*/
if( $updateFlag === 1 ):
$returnCss = $css_code;

$css_code = addslashes( $css_code );
if( $wpdb-&gt;update( $table_name, ['text' =&gt; $css_code, 'time' =&gt; date('YmdHis')], ['name' =&gt; 'parent_styles'] ) ){
// echo '<!-- STYLE CACHE UPDATED -->';
}
endif;

foreach ($deregHandle as $handle) {
// print "<!-- DEREGISTERING $handle -->";
wp_deregister_style($handle);
}
// print '<!-- RETURN CSS is ' . $returnCss .' -->';

wp_add_inline_style( 'custom-styles', $returnCss );

// # -- FUTURE UPGRADE
// wp_enqueue_style('merged-style', get_stylesheet_directory_uri() . '/css/merged-style.css');

}
add_action('wp_print_styles', 'parent_style_cache');