2023-06-11 / 675阅
要在 WordPress 中压缩 HTML 代码,可以使用插件或手动添加代码。
使用插件:
手动添加代码:
将以下代码添加到 WordPress 主题的 functions.php 文件中:
// 压缩 HTML 代码
function compress_html() {
    // 开始输出压缩
    ob_start('html_compress_callback');
}
// 结束 HTML 输出压缩
function html_compress_callback($buffer) {
    // 清除注释
    $buffer = preg_replace('/<!--(.|s)*?-->/', '', $buffer);
    // 清除空格
    $buffer = str_replace(array("rn", "r", "n", "t"), '', $buffer);
    // 返回结果
    return $buffer;
}
// 添加钩子,启动压缩
add_action('after_setup_theme', 'compress_html'); 代码功能说明:
compress_html() 函数将启动 HTML 输出压缩。html_compress_callback() 函数将接收 HTML 输出缓冲区的内容,并清除注释和空格。add_action('after_setup_theme', 'compress_html') 将添加一个钩子,在主题设置完成后,执行 HTML 输出压缩。注意事项:
阅读文章或者观看视频过程中有任何问题,请下方留言或者联系我Q248758228