Skip to content

WordPress 性能优化

性能优化概述

性能指标

指标目标值说明
TTFB< 200ms首字节时间
FCP< 1.8s首次内容绘制
LCP< 2.5s最大内容绘制
CLS< 0.1累积布局偏移
FID/INP< 100ms交互延迟

核心优化原则

  1. 减少请求数量 - 合并、压缩资源
  2. 减小文件体积 - 压缩 CSS/JS/图片
  3. 缩短加载距离 - CDN、本地化
  4. 优化执行时间 - 数据库查询、PHP 代码

服务器配置优化

PHP 配置 (php.ini)

ini
; 内存限制
memory_limit = 256M

; 执行时间
max_execution_time = 300

; 上传大小
upload_max_filesize = 64M
post_max_size = 64M

; OPcache
opcache.enable = 1
opcache.memory_consumption = 256
opcache.interned_strings_buffer = 16
opcache.max_accelerated_files = 20000

; 真实路径缓存
realpath_cache_size = 4096K
realpath_cache_ttl = 600

WordPress 配置 (wp-config.php)

php
<?php
// 内存限制
define('WP_MEMORY_LIMIT', '256M');
define('WP_MAX_MEMORY_LIMIT', '512M');

// 自动更新
define('AUTOMATIC_UPDATER_DISABLED', false);
define('WP_AUTO_UPDATE_CORE', 'minor');

// 心跳控制
define('DISABLE_HEARTBEAT', false);
define('HEARTBEAT_INTERVAL', 60);

// 自动保存
define('AUTOSAVE_INTERVAL', 160);

// 文章修订版
define('WP_POST_REVISIONS', 5);

// 垃圾回收
define('EMPTY_TRASH_DAYS', 7);

// 调试模式(生产环境关闭)
define('WP_DEBUG', false);
?>

Nginx 配置

nginx
# 启用压缩
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_proxied any;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml;
gzip_disable "MSIE [1-6]\.";

# 浏览器缓存
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2)$ {
    expires 30d;
    add_header Cache-Control "public, no-transform";
}

# WordPress 规则
location / {
    try_files $uri $uri/ /index.php?$args;
}

# 禁止访问敏感文件
location ~ /\. {
    deny all;
}

数据库优化

优化查询

php
<?php
// 在 functions.php 中优化

// 1. 移除不必要的小工具
function remove_default_widgets() {
    unregister_widget('WP_Widget_Pages');
    unregister_widget('WP_Widget_Calendar');
    unregister_widget('WP_Widget_Archives');
    unregister_widget('WP_Widget_Links');
    unregister_widget('WP_Widget_Meta');
    unregister_widget('WP_Widget_Search');
}
add_action('widgets_init', 'remove_default_widgets', 11);

// 2. 禁用 REST API(如果不需要)
add_filter('rest_enabled', '__return_false');
add_filter('rest_jsonp_enabled', '__return_false');

// 3. 移除不必要的 REST API 路由
add_filter('rest_endpoints', function($endpoints) {
    if (isset($endpoints['/wp/v2/users'])) {
        unset($endpoints['/wp/v2/users']);
    }
    if (isset($endpoints['/wp/v2/users/(?P<id>[\d]+)'])) {
        unset($endpoints['/wp/v2/users/(?P<id>[\d]+)']);
    }
    return $endpoints;
});

// 4. 优化搜索查询
function optimize_search($query) {
    if (!is_admin() && $query->is_search()) {
        $query->set('search_orderby_title', true);
        $query->set('posts_per_page', 10);
    }
    return $query;
}
add_filter('pre_get_posts', 'optimize_search');
?>

清理数据库

php
<?php
/**
 * 数据库清理函数
 */
function cleanup_database() {
    global $wpdb;
    
    // 删除孤立 postmeta
    $wpdb->query("
        DELETE pm FROM {$wpdb->postmeta} pm
        LEFT JOIN {$wpdb->posts} p ON pm.post_id = p.ID
        WHERE p.ID IS NULL
    ");
    
    // 删除孤立 commentmeta
    $wpdb->query("
        DELETE cm FROM {$wpdb->commentmeta} cm
        LEFT JOIN {$wpdb->comments} c ON cm.comment_id = c.comment_ID
        WHERE c.comment_ID IS NULL
    ");
    
    // 清理过期 transients
    $wpdb->query("
        DELETE FROM {$wpdb->options}
        WHERE option_name LIKE '_transient_timeout_%'
        AND option_value < " . time()
    );
    
    $wpdb->query("
        DELETE FROM {$wpdb->options}
        WHERE option_name LIKE '_transient_%'
        AND option_name NOT LIKE '_transient_timeout_%'
        AND option_value LIKE '%\"expiration\":%'
        AND CAST(SUBSTRING(option_value, LOCATE('\"expiration\":', option_value) + 14, 10) AS UNSIGNED) < " . time()
    );
    
    // 优化表
    $wpdb->query("OPTIMIZE TABLE {$wpdb->posts}");
    $wpdb->query("OPTIMIZE TABLE {$wpdb->postmeta}");
}
?>

缓存策略

对象缓存

php
<?php
// 使用 Transients(临时缓存)
set_transient('my_data', $data, HOUR_IN_SECONDS);
$data = get_transient('my_data');
delete_transient('my_data');

// 使用 WP Cache
wp_cache_set('key', $data, 'group', HOUR_IN_SECONDS);
$data = wp_cache_get('key', 'group');

// 缓存数据库查询
function get_cached_posts($args) {
    $cache_key = md5(serialize($args));
    $cached = wp_cache_get($cache_key, 'my_posts');
    
    if ($cached === false) {
        $cached = new WP_Query($args);
        wp_cache_set($cache_key, $cached, 'my_posts', 5 * MINUTE_IN_SECONDS);
    }
    
    return $cached;
}
?>

页面缓存

使用 WP Super CacheW3 Total Cache

php
<?php
// 启用页面缓存(插件配置)
// 1. WP Super Cache 配置
define('WPCACHEHOME', WP_CONTENT_DIR . '/plugins/wp-super-cache/');

// 2. W3 Total Cache 配置
define('WP_CACHE', true);

// 手动启用页面缓存
function enable_page_cache() {
    if (!defined('DONOTCACHEPAGE')) {
        define('DONOTCACHEPAGE', true);
    }
}
?>

Redis/Memcached 对象缓存

php
<?php
// wp-config.php 配置
define('WP_REDIS_HOST', '127.0.0.1');
define('WP_REDIS_PORT', 6379);
define('WP_REDIS_DATABASE', 0);
define('WP_REDIS_PREFIX', 'wp_');

// 或使用插件:
// - Redis Object Cache
// - Memcached Object Cache
?>

图片优化

图片最佳实践

php
<?php
// 在 functions.php 中优化图片加载

// 1. 延迟加载(WordPress 5.5+ 自动支持)
add_filter('wp_img_tag_add_loading_attr', '__return_false'); // 如需禁用

// 2. 响应式图片 srcset
add_filter('wp_calculate_image_srcset', function($sources) {
    // 只保留需要的尺寸
    return array_filter($sources, function($source) {
        return $source['descriptor'] === 'w' && 
               in_array($source['value'], array(640, 750, 828, 1080, 1200, 1920, 2048, 3840));
    });
});

// 3. 使用 WebP 格式
function webp_upload_mime_types($mimes) {
    $mimes['webp'] = 'image/webp';
    return $mimes;
}
add_filter('upload_mimes', 'webp_upload_mime_types');

// 4. 中断大图片上传
function prevent_large_uploads($file) {
    $image_sizes = get_intermediate_image_sizes();
    $max_width = 0;
    $max_height = 0;
    
    foreach ($image_sizes as $size) {
        $sizes = wp_get_attachment_image_src(0, $size);
        if ($sizes) {
            $max_width = max($max_width, $sizes[1]);
            $max_height = max($max_height, $sizes[2]);
        }
    }
    
    if (empty($max_width)) {
        return $file;
    }
    
    $image = @getimagesize($file['tmp_name']);
    
    if ($image && ($image[1] > $max_height * 2 || $image[2] > $max_width * 2)) {
        $file['error'] = '图片尺寸过大,请压缩后上传。';
    }
    
    return $file;
}
add_filter('wp_handle_upload_prefilter', 'prevent_large_uploads');
?>

图片压缩插件

插件功能评分
Smush自动压缩、优化⭐ 4.8
ShortPixelWebP 支持⭐ 4.9
Imagify多格式支持⭐ 4.7
EWWW Image Optimizer批量优化⭐ 4.6

CSS 和 JavaScript 优化

优化资源加载

php
<?php
// 1. 移除不必要的 CSS/JS
function dequeue_unnecessary_styles() {
    // 移除 Gutenberg CSS
    wp_dequeue_style('wp-block-library');
    
    // 移除 WooCommerce 样式(如果不用)
    wp_dequeue_style('woocommerce-layout');
    wp_dequeue_style('woocommerce-smallscreen');
    wp_dequeue_style('woocommerce-general');
}
add_action('wp_enqueue_scripts', 'dequeue_unnecessary_styles', 999);

// 2. 延迟加载 JavaScript
function defer_parsing_of_js($tag, $handle, $src) {
    // 排除已延迟的脚本
    $defer_scripts = array('jquery-core', 'main-script');
    
    if (!in_array($handle, $defer_scripts)) {
        return str_replace(' src', ' defer src', $tag);
    }
    return $tag;
}
add_filter('script_loader_tag', 'defer_parsing_of_js', 10, 3);

// 3. 异步加载脚本
function async_load_scripts($tag, $handle, $src) {
    $async_scripts = array('analytics', 'adsense');
    
    if (in_array($handle, $async_scripts)) {
        return str_replace(' src', ' async src', $tag);
    }
    return $tag;
}
add_filter('script_loader_tag', 'async_load_scripts', 10, 3);

// 4. 仅在需要时加载脚本
function conditionally_load_scripts() {
    if (!is_page('contact')) {
        wp_dequeue_style('contact-form-7');
        wp_dequeue_script('contact-form-7');
    }
}
add_action('wp_enqueue_scripts', 'conditionally_load_scripts', 999);
?>

关键 CSS

html
<!-- 在 <head> 中内联关键 CSS -->
<style>
/* Above-the-fold 关键样式 */
body { margin: 0; font-family: system-ui; }
.header { padding: 20px; background: #21759b; }
</style>

<!-- 异步加载完整 CSS -->
<link rel="preload" href="/wp-content/themes/theme/style.css" as="style" 
      onload="this.onload=null;this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="/wp-content/themes/theme/style.css"></noscript>

CDN 配置

使用 CDN

php
<?php
// wp-config.php 配置 CDN
define('WP_CONTENT_URL', 'https://cdn.example.com/wp-content');
define('WP_PLUGIN_URL', 'https://cdn.example.com/wp-content/plugins');

// 或使用插件:
// - WP Super Cache(CDN 支持)
// - WP Fastest Cache
// - Cloudflare
?>

本地化字体

php
<?php
// 在 functions.php 中

// 1. 预连接字体源
function add_preconnect_resources($urls, $relation_type) {
    if (is_admin()) {
        return $urls;
    }
    
    $urls_to_add = array();
    
    if ($relation_type === 'preconnect') {
        $urls_to_add[] = array(
            'href' => 'https://fonts.googleapis.com',
            'crossorigin' => 'anonymous'
        );
        $urls_to_add[] = array(
            'href' => 'https://fonts.gstatic.com',
            'crossorigin' => 'anonymous'
        );
    }
    
    return array_merge($urls, $urls_to_add);
}
add_filter('wp_resource_hints', 'add_preconnect_resources', 10, 2);

// 2. 优化 Google Fonts 加载
function optimize_google_fonts() {
    wp_dequeue_style('twentytwentyone-fonts');
}
add_action('wp_enqueue_scripts', 'optimize_google_fonts', 20);
?>

性能监控

使用 Query Monitor

php
<?php
// 启用调试信息
define('SAVEQUERIES', true);
define('SCRIPT_DEBUG', true);
?>

性能检测代码

php
<?php
// 在页面底部显示性能信息
function display_performance_stats() {
    if (!current_user_can('manage_options')) {
        return;
    }
    
    $stats = array();
    
    // 页面生成时间
    $stats['生成时间'] = timer_stop(0, 3) . ' 秒';
    
    // 内存使用
    $stats['内存使用'] = size_format(memory_get_usage());
    
    // 数据库查询数
    global $wpdb;
    $stats['查询次数'] = $wpdb->num_queries . ' 次';
    
    // 输出
    echo '<div style="background:#f0f0f0;padding:10px;margin:20px 0;">';
    echo '<strong>性能统计</strong><br>';
    foreach ($stats as $label => $value) {
        echo $label . ': ' . $value . '<br>';
    }
    echo '</div>';
}
add_action('wp_footer', 'display_performance_stats');
?>

完整优化清单

快速优化(立即实施)

□ 安装缓存插件
□ 启用 Gzip 压缩
□ 优化图片
□ 清理数据库
□ 启用浏览器缓存
□ 减少插件数量
□ 更新所有组件

中期优化(1-2 周)

□ 配置 CDN
□ 优化 CSS/JS
□ 数据库优化
□ 延迟加载非关键资源
□ 实现关键 CSS

长期优化(持续进行)

□ 迁移到更好的主机
□ 考虑静态站点生成
□ 实施 HTTP/2
□ 使用边缘计算
□ 定期监控性能

基于 WordPress官方文档 构建