- 8 段可以直接用的代码,免费给 Elementor 网站再提速。先从最安全的 3 段开始,其余按需。
- 适合已经装好缓存插件、想再手动优化一步的站长。需要懂一点点 PHP 或愿意复制粘贴。
- 这些代码跟 LiteSpeed Cache 是互补关系,不是替代。
- ⚠️ 套用前一定要先备份网站。
先搞懂
代码要放在哪里
两种放法,建议用第二种:
- 主题的
functions.php:直接改,写错整个网站可能白屏。 - Code Snippets 这类插件:每段代码单独开关,出错时一键停用,更安全。
这些代码在做什么
多数是 WordPress 的过滤器(filter):在 WordPress 处理某件事的时候插进来,改掉它的默认做法。例如「不要加载 Google Fonts」「图片补上尺寸」。
开始之前
- 先备份网站。网站本身若已有别的问题,加代码可能冲突,备份才能还原。
- 先在暂存或本地环境试,方法见《怎么测试 WordPress 网站的功能、速度与安全性》。
- 一次只加一段,加完看前台有没有异常。
先用哪几段
| 层级 | 代码片段 | 适合谁 |
|---|---|---|
| 建议先用 | 限制文章修订数量 | 所有网站 |
| 建议先用 | 确保 Web 字体正常显示 | 用 Elementor Pro 自定义字体 |
| 建议先用 | 移除 Google Fonts | 已改用本地字体或系统字体 |
| 看情况 | 停用懒加载 | 缓存插件自己有懒加载 |
| 看情况 | 给图片补上固定宽高 | 想改善页面跳动(CLS) |
| 看情况 | 后台加「清除缓存」按钮 | 常要调试 |
| 开发者 | 移除未使用的 JS | 会改代码的人 |
| 开发者 | 精简 CSS 文件 | 没装 CSS 优化插件 |
逐一细看
这一节是代码本身,不用全部读,从上面的表挑要用的那一段展开。
限制文章修订数量把每篇文章最多保存的历史版本限制在 3 个。
把每篇文章最多保存的历史版本限制在 3 个。
define('WP_POST_REVISIONS', 3);
- 减少数据库体积,提升整体性能。
- 跟 LiteSpeed Cache 的 Database →「文章修订最大次数」是同一件事,两边挑一个设置,不用重复,见《数据库、爬虫、工具箱与心跳设置》。
确保 Web 字体正常显示字体还没加载好时,先用系统字体顶上,避免访客看到空白文字。
字体还没加载好时,先用系统字体顶上,避免访客看到空白文字。
add_filter( 'elementor_pro/custom_fonts/font_display', function( $current_value, $font_family, $data ) {
return 'swap';
}, 10, 3 );
- 把 Elementor Pro 自定义字体的
font-display设成swap。 - 改善用户体验和首次内容绘制(FCP)分数。
移除 Google Fonts阻止 Elementor 自动加载 Google Fonts,减少外…
阻止 Elementor 自动加载 Google Fonts,减少外部请求。
add_filter( 'elementor/frontend/print_google_fonts', '__return_false' );
📌 只适合已经改用本地字体或系统字体的网站。否则原本设定的 Google 字体会显示不出来。
停用懒加载全站关闭 WordPress 内建的图片懒加载。
全站关闭 WordPress 内建的图片懒加载。
add_filter( 'wp_lazy_loading_enabled', '__return_false' );
📌 一般不建议关闭,懒加载通常对性能有益。只有在你用缓存插件(如 LiteSpeed Cache)自己的懒加载时才用,避免两边同时处理造成冲突。
给图片补上固定宽高自动给缺少 width / height 的图片补上尺寸,改善页面跳…
自动给缺少 width / height 的图片补上尺寸,改善页面跳动(CLS)。
add_filter( 'the_content', 'add_image_dimensions' );
function add_image_dimensions( $content ) {
preg_match_all( '/<img[^>]+>/i', $content, $images );
if ( count( $images ) < 1 ) {
return $content;
}
foreach ( $images[0] as $image ) {
preg_match_all( '/(alt|title|src|width|class|id|height)=("[^"]*")/i', $image, $img );
if ( ! in_array( 'src', $img[1] ) ) {
continue;
}
// 检查图片是否属于要排除的 class
if ( in_array( 'class', $img[1] ) ) {
$classes = $img[2][ array_search( 'class', $img[1] ) ];
if ( preg_match( '/\b(elementor-widget-image-carousel|swiper|swiper-container)\b/i', $classes ) ) {
continue;
}
}
if ( ! in_array( 'width', $img[1] ) || ! in_array( 'height', $img[1] ) ) {
$src = $img[2][ array_search( 'src', $img[1] ) ];
$alt = in_array( 'alt', $img[1] ) ? ' alt=' . $img[2][ array_search( 'alt', $img[1] ) ] : '';
$title = in_array( 'title', $img[1] ) ? ' title=' . $img[2][ array_search( 'title', $img[1] ) ] : '';
$class = in_array( 'class', $img[1] ) ? ' class=' . $img[2][ array_search( 'class', $img[1] ) ] : '';
$id = in_array( 'id', $img[1] ) ? ' id=' . $img[2][ array_search( 'id', $img[1] ) ] : '';
list( $width, $height, $type, $attr ) = getimagesize( str_replace( "\"", "", $src ) );
$image_tag = sprintf( '<img src=%s%s%s%s%s width="%d" height="%d" />', $src, $alt, $title, $class, $id, $width, $height );
$content = str_replace( $image, $image_tag, $content );
}
}
return $content;
}
- 扫描文章内容里的
<img>,读取图片实际尺寸后补上。 - 代码已排除 Elementor 轮播图的 class(
elementor-widget-image-carousel、swiper、swiper-container),因为轮播图尺寸是动态的,硬加固定宽高会弄坏轮播。 - 📌 用的是其他非 Elementor 原生的轮播插件,要把它的 class 也加进排除清单。
在后台工具栏加「清除缓存」按钮一键清空 WordPress 的对象缓存,调试时不用每次跑去设置页。
一键清空 WordPress 的对象缓存,调试时不用每次跑去设置页。
/*
Plugin Name: Purge Cache
Description: 在 WordPress 后台加一个清除对象缓存的按钮
*/
add_action( 'admin_bar_menu', 'add_purge_cache_button', 999 );
function add_purge_cache_button( $wp_admin_bar ) {
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
$args = array(
'id' => 'purge-cache',
'title' => 'Purge Cache',
'href' => '#',
'meta' => array( 'class' => 'purge-cache' )
);
$wp_admin_bar->add_node( $args );
}
add_action( 'admin_footer', 'add_purge_cache_script' );
function add_purge_cache_script() {
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
?>
<script>jQuery(document).ready(function($){$('#wp-admin-bar-purge-cache').click(function(){if(confirm('Are you sure you want to purge the cache?')){$.ajax({url:'<?php echo admin_url( 'admin-ajax.php' ); ?>',data:{action:'purge_cache',},success:function(){alert('Cache purged successfully!');},error:function(){alert('An error occurred while purging the cache.');}});}});});</script>
<?php
}
add_action( 'wp_ajax_purge_cache', 'purge_cache_callback' );
function purge_cache_callback() {
global $wp_object_cache;
if ( ! current_user_can( 'manage_options' ) ) {
wp_die();
}
wp_cache_flush();
wp_die();
}
- 只有管理员(
manage_options权限)看得到、点得了,点击后会先弹出确认框。 - 清的是对象缓存(
wp_cache_flush()),不是 LiteSpeed Cache 的页面缓存。
移除未使用的 JS(开发者模板)在指定页面移除不需要的脚本,管理员账号不受影响。
在指定页面移除不需要的脚本,管理员账号不受影响。
function wp_remove_scripts() {
// 检查是否为管理员
if (current_user_can( 'update_core' )) {
return;
}
else {
// 指定要处理的页面
if ( is_page( 'homepage' ) ) {
// 移除脚本
wp_dequeue_style( 'jquery-ui-core' );
}
}
}
add_action( 'wp_enqueue_scripts', 'wp_remove_scripts', 99 );
💡 这是模板。要把 is_page('homepage') 和 wp_dequeue_style('jquery-ui-core') 换成你网站实际要处理的页面和脚本。
精简 CSS 文件(Elementor)压缩 CSS 里的空白和换行,但保留 Elementor 自己的核心…
压缩 CSS 里的空白和换行,但保留 Elementor 自己的核心文件。
function exclude_specific_css_files($src, $handle) {
// 要排除、不参与精简的 CSS 文件清单
$excluded_css_files = array(
'/wp-content/plugins/elementor/assets/css/frontend-lite.min.css',
'/wp-content/plugins/elementor-pro/assets/css/frontend-lite.min.css',
);
// 检查当前 CSS 文件网址是否在排除清单里
foreach ($excluded_css_files as $excluded_css_file) {
if (strpos($src, $excluded_css_file) !== false) {
return $src; // 保留原始未压缩的 CSS 文件
}
}
// 不在排除清单里的话,正常进行压缩
return minify_css_content($src);
}
function minify_css_content($content) {
$content = preg_replace('/\s+/', ' ', $content); // 移除多余空白
$content = str_replace(array("\r\n", "\r", "\n", "\t"), '', $content); // 移除换行和缩进
return $content;
}
add_filter('style_loader_src', 'exclude_specific_css_files', 10, 2);
- Elementor 和 Elementor Pro 的核心 CSS(
frontend-lite.min.css)被排除,它们结构特殊,用这种简易压缩容易出问题。 - 📌 已经在用 PhastPress 这类 CSS / JS 优化插件,就不用这段,避免功能重叠冲突。
- 📌 原文把它叫「移除未使用的 CSS」,但这段代码只压缩空白,不会删掉没用到的 CSS。要删未使用的 CSS,用 LiteSpeed Cache 的 UCSS,见《页面优化设置详解》。
做完检查
- 前台首页、文章页、有轮播图的页面都打开看一遍,排版和功能正常。
- 后台能正常登录和编辑。
- 用 PageSpeed Insights 对比前后分数,方法见《用 PageSpeed Insights API 监控网站性能》。
- 出问题:在 Code Snippets 里停用刚加的那一段。直接改
functions.php的话,要还原备份。
常见误区
- ❌ 加代码前没备份——代码直接改渲染逻辑,冲突时网站可能白屏,备份是最快的还原办法。
- ❌ 「停用懒加载」代码 + 缓存插件的懒加载一起开——两边同时处理容易冲突,二选一。
- ❌ 图片补尺寸的代码直接套用到别的轮播插件——只排除了 Elementor 的常见轮播 class,其他轮播要自己加进排除清单。
Sources
Blog / Website:
官方文档: