Skip to content

Instantly share code, notes, and snippets.

@ksk1015
Created December 14, 2018 19:10
Show Gist options
  • Save ksk1015/25ab72ad11ac4956dc3f1dc245b6cd82 to your computer and use it in GitHub Desktop.
Save ksk1015/25ab72ad11ac4956dc3f1dc245b6cd82 to your computer and use it in GitHub Desktop.
function my_enqueue_inline_style ( $handle, $src = '', $deps = array(), $ver = false, $media = 'all' ) {
if ( $src ) {
wp_enqueue_style( $handle, $src, $deps, false, $media );
}
add_filter( 'style_loader_tag', function ( $html, $this_handle, $href, $media ) use ($handle) {
if ($this_handle !== $handle) {
return $html;
}
$css_url = explode('?', $href)[0];
$css_path = str_replace(site_url(), ABSPATH, $css_url);
$base_dir = dirname($css_path) . '/';
$css = file_get_contents( $css_path );
// convert relative url to absolute
$css = preg_replace_callback("/url\((?![\'\"]?[http:|data:|\/])[\'\"]?(.+?)[\'\"]?\)/s", function ($matches) use ($base_dir) {
$relative = $matches[1];
while ( strpos($relative, '../') === 0 ) {
$relative = substr($relative, 3);
$base_dir = preg_replace('/[^\/]+?\/$/', '', $base_dir);
}
if ( strpos($relative, './') === 0 ) {
$relative = substr($relative, 2);
}
$path = $base_dir . $relative;
$url = str_replace(ABSPATH, site_url(), $path);
return "url('$url')";
}, $css);
// Minify
$css = preg_replace('/\/\*((?!\*\/).)*\*\//', '', $css);
$css = preg_replace('/\s{2,}/', ' ', $css);
$css = preg_replace('/\s*([:;{}])\s*/', '$1', $css);
$css = preg_replace('/;}/', '}', $css);
return "<style media='$media'>/* $url */\n$css\n</style>\n";
}, 10, 4 );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment