WP TOOLS

EP09. “Elementor 网站提速代码片段合集”

首页 建站工具 Performance · LiteSpeed Cache
约 20 分钟·
🔒 登录后可标记已读

这篇笔记整理几段可以直接用在 Elementor 网站上、免费提升网站速度的代码片段(Code Snippets),适合有基本 PHP 概念、想在缓存插件之外再进一步手动优化网站的站长。⚠️ 这些代码通常加到主题的 functions.php,或用 Code Snippets 这类插件建立自定义片段来跑,跟 LiteSpeed Cache 这类缓存插件是互补关系,不是替代关系。

重点内容

⚠️ 套用任何代码片段前务必先备份网站——如果网站本身有其他代码/插件/设置上的问题,套用这些片段有可能造成冲突,出问题时才能还原。


移除 Google Fonts(仅限 Elementor 网站)

add_filter( 'elementor/frontend/print_google_fonts', '__return_false' );

阻止 Elementor 自动加载 Google Fonts,减少外部请求,适合已经改用本地字体或系统字体的网站。


限制文章修订数量

define('WP_POST_REVISIONS', 3);

把 WordPress 保存的文章修订版本上限设成 3,减少数据库体积,提升整体性能(这个设置的效果跟 LiteSpeed Cache 数据库分类里的「文章修订最大次数」是同一件事,两边挑一个地方设置即可,不需要重复设置)。


确保 Web 字体正常显示(Elementor 网站)

add_filter( 'elementor_pro/custom_fonts/font_display', function( $current_value, $font_family, $data ) {
	return 'swap';
}, 10, 3 );

把 Elementor Pro 自定义字体的 font-display 设成 swap,字体还没加载完成时先用系统字体顶上,避免访客看到空白文字,改善用户体验和 FCP 分数。


停用懒加载(Stop Lazy Load)

add_filter( 'wp_lazy_loading_enabled', '__return_false' );

全站关闭 WordPress 内建的图片懒加载功能。📌 一般不建议直接关闭懒加载(懒加载通常对性能有益),这段代码适合搭配专门的缓存/优化插件(比如 LiteSpeed Cache)自己的懒加载功能一起用时,避免两边同时处理懒加载造成冲突。


移除未使用的 JS(示范:jQuery UI)

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 );

示范怎么在指定页面(例子里是首页)移除不需要的脚本/样式(例子里是 jQuery UI),管理员账号不受影响。💡 这段代码是给开发者的模板,实际使用时要把 is_page('homepage')wp_dequeue_style('jquery-ui-core') 换成自己网站实际要处理的页面和脚本。


给图片补上固定宽高(适合有 Elementor 轮播图的网站)

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;
}

自动扫描文章内容里缺少 width/height 属性的 <img> 标签,读取图片实际尺寸后补上——能改善 CLS(累积布局偏移)分数。📌 代码里特别排除了 Elementor 轮播图相关的 class(elementor-widget-image-carouselswiperswiper-container),因为轮播图本身的尺寸是动态的,强行加固定宽高反而会弄坏轮播效果。


在后台工具栏加一个「清除缓存」按钮

/*
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 权限)能看到并点击这个按钮,点击后会弹出确认框,确认后透过 AJAX 清空 WordPress 的对象缓存(wp_cache_flush()),方便调试改动是否生效,不用每次都跑去缓存插件的设置页手动清缓存


移除未使用的 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);

📌 这段代码如果网站已经在用 PhastPress 这类专门做 CSS/JS 优化的插件,可以忽略不用(避免功能重叠冲突)。Elementor 和 Elementor Pro 自身的核心 CSS 文件被排除在这段自定义精简逻辑之外,因为这两个文件本身结构特殊,强行用这段简易压缩逻辑处理容易出问题。

常见误区

  • ❌ 套用代码片段前没有先备份网站——这些代码直接改动 functions.php 或前端渲染逻辑,一旦跟其他插件/代码冲突,网站可能直接白屏,备份是唯一能快速复原的方法
  • ❌ 同时用这里的「停用懒加载」代码 + 缓存插件自己的懒加载功能——两边同时处理懒加载容易冲突,应该二选一
  • ❌ 图片尺寸修补代码直接套用到有 Elementor 轮播图的页面而不做排除——代码本身已经排除了常见轮播图 class,但如果用的是其他非 Elementor 原生的轮播插件,可能需要额外把对应 class 加进排除清单
  • 💡 「限制文章修订数量」这段代码和 LiteSpeed Cache 数据库分类里的同名设置效果重复,两边选一个地方设置就好,不用重复设置

Sources

Blog / Website:

  1. WordPress Page Speed Optimization Code Snippets (Elementor) — https://learn.websquadron.co.uk/wordpress-page-speed/

官方文档:

  1. How to Speed Up a Slow Elementor Website — https://elementor.com/help/speed-up-a-slow-site/