function wpunion_combine_assets($type = 'style') {
if (WP_DEBUG || WU_DEVELOPMENT) return;
$is_combine_style = $type === 'style';
global $wp_styles, $wp_scripts;
$obj = $is_combine_style ? $wp_styles : $wp_scripts;
if (empty($obj->queue)) return;
$base_dir = WP_CONTENT_DIR . '/wpunion-work/combined/';
$base_url = content_url('/wpunion-work/combined/');
if (!is_dir($base_dir)) wp_mkdir_p($base_dir);
$excludes = ['xx']; //要排除的文件句柄
$sources = []; // 用于生成唯一 hash
$targets = []; // 将要合并的资源
foreach ($obj->queue as $handle) {
if (in_array($handle, $excludes)) continue;
$reg = $obj->registered[$handle] ?? '';
if (!$reg) continue;
$src = $reg->src ?? '';
if (!$src) continue;
// 只处理本站资源
if (strpos($src, home_url()) === false && strpos($src, get_stylesheet_directory_uri()) === false && strpos($src, get_template_directory_uri()) === false) continue;
$path = str_replace(home_url('/'), ABSPATH, $src);
$path = wp_normalize_path($path);
if (file_exists($path)) {
$sources[] = $src . $reg->ver ?? '';
$targets[$handle] = $path;
}
}
if (!$targets) return;
$hash = md5(json_encode($sources));
$ext = $is_combine_style ? '.css' : '.js';
$filename = "wpunion-combined-{$hash}{$ext}";
$filepath = $base_dir . $filename;
$fileurl = $base_url . $filename;
// 若合并文件不存在 → 生成
if (!file_exists($filepath)) {
$buffer = '';
foreach ($targets as $handle => $path) {
$buffer .= "\n/** wpunion combine {$handle} */\n" . file_get_contents($path);
}
file_put_contents($filepath, $buffer);
}
// 清除原有资源
foreach ($targets as $handle => $path) {
if ($is_combine_style) {
wp_dequeue_style($handle);
wp_deregister_style($handle);
}
else {
wp_dequeue_script($handle);
wp_deregister_script($handle);
}
}
// 引入合并资源
if ($is_combine_style) {
wp_enqueue_style("wpunion-{$hash}", $fileurl, [], filemtime($filepath));
}
else {
wp_enqueue_script("wpunion-{$hash}", $fileurl, [], filemtime($filepath), true);
}
}
// 合并 CSS
add_action('wp_print_styles', function () {
wpunion_combine_assets('style');
}, PHP_INT_MAX);
// 合并 JS
add_action('wp_print_scripts', function () {
wpunion_combine_assets('script');
}, PHP_INT_MAX);