技術ブログ

【コピペOK】HTMLをMinify化してコメントアウトも削除するようにするコード
2024.05.18

【コピペOK】HTMLをMinify化してコメントアウトも削除するようにするコード

2024.05.18 13

WordPressでプラグインを使ってHTMLコードなどの圧縮をしなくてもfunctions.phpに記載して圧縮しコメントアウトも削除してコードを出力するコードの備忘録  

function minify_html($content) {

    $content = preg_replace('/>\s+</', '><', $content);
    $content = preg_replace('/<!--(.|\s)*?-->/', '', $content);

    $content = preg_replace_callback('/(<script[^>]*>)(.*?)(<\/script>)/is', function ($matches) {
        $script_content = preg_replace('/\/\/ .*$/m', '', $matches[2]); // Remove "// "
        return $matches[1] . preg_replace('/\s+/', ' ', $script_content) . $matches[3];
    }, $content);


    $content = preg_replace_callback('/(<style[^>]*>)(.*?)(<\/style>)/is', function ($matches) {
        return $matches[1] . preg_replace('/\s+/', ' ', $matches[2]) . $matches[3];
    }, $content);

    return $content;
}

add_action('template_redirect', function () {
    ob_start('minify_html');
});

// Minify the_content
add_filter('the_content', 'minify_html');