【WordPress】优化汇总
本文最后更新于 118 天前,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

wordpress优化汇总

前言

收集网上关于 WordPress 的实用优化技巧,便于后续使用查询。

服务器配置

WordPress 作为一款强大的程序,对性能的要求自然不低,服务器计算能力会直接影响到网站速度及并发。

  • PHP:推荐使用 PHP7 及以上版本,性能有极大提升
  • 启用 PHP OPCache 扩展,PHP 代码编译加速优化
  • MySQL:推荐使用 MySQL 5.6 及以上版本
  • 合理优化 MySQL 参数
  • 使用 PHP Memcached 扩展,内存缓存加速
  • 使用 Redis 加速网站访问速度

以下为在宝塔面板内的安装和设置操作,设置完成后,重启服务生效。

  1. 安装 PHP 扩展

    wordpress优化汇总-1

    • 访问 Github 项目页面下载插件包:https://github.com/tollmanz/wordpress-pecl-memcached-object-cache
    • 下载并解压得到的 object-cache.php,上传到 wp-content 目录即可开启 Memcached 缓存。
    • 编辑 wp-config.php,添加如下内容,使 Memcached 生效
      /** Memcached Cache */
      define('ENABLE_CACHE', true);
      define('WP_CACHE', true);
      define('WP_CACHE_KEY_SALT', '5iehome.cc');
  2. PHP Session 配置选择 redis 存储模式

    wordpress优化汇总-2

  3. 根据自己服务器情况,选择 MySQL 性能优化方案

    wordpress优化汇总-3

优化 MySQL 5.7 的内存占用

编辑 /etc/mysql/mysql.conf.d/mysqld.cnf,在 [mysqld] 下方添加如下代码

[mysqld]
# Memory optimization
performance_schema_max_table_instances=200
table_definition_cache=100
table_open_cache=100

测试 WordPress 网站性能

程序优化

修改配置文件

WordPress 中许多不必要的功能可以通过修改配置文件的方式关闭。 注意:在进行相关操作前务必备份好源文件!

  • wp-config.php 文件后添加下列内容
//WordPress自定义优化项。
define('WP_DEBUG', false);  //关闭DEBUG
define('AUTOSAVE_INTERVAL', 86400);  //关闭自动保存
define('WP_POST_REVISIONS', false);  //关闭修订
define('DISALLOW_FILE_EDIT', true);  //关闭文件修改
define('FS_CHMOD_DIR', (0755 & ~ umask()));  //目录权限755
define('FS_CHMOD_FILE', (0644 & ~ umask()));  //文件权限644
//禁止更新(不建议)
//define('AUTOMATIC_UPDATER_DISABLED', true);
//define('WP_AUTO_UPDATE_CORE', false);
  • 在当前主题目录中 function.php 后添加下列内容
//WordPress主题 functions.php 优化项
//引入方式:在主题functions.php后添加

//关闭谷歌字体
function xintheme_ remove_ gutenberg_ styles(Stranslation,$text, $context,$domain)
{
if($context != 'Google Font Name Tand Variants’|| $text != 'Noto Serif:400,400i,700,700i') {
return $translation;
}
return 'off';
}

//彻底关闭自动更新
add_ filter(' automatic_ updater_disabled', '_return_true');

//关闭更新检查定时作业
remove_ action('init', 'wp_schedule_update_checks');

//移除已有的版本检查定时作业
wp_clear_scheduled_hook('wp_version_check');

//移除已有的插件更新定时作业
wp_clear_scheduled_hook('wp_update_plugins');

//移除已有的主题更新定时作业
wp_clear_scheduled_hook('wp_update_themes');

//移除已有的自动更新定时作业
wp_clear_scheduled_hook('wp_maybe_auto_update');

//移除后台内核更新检查
remove_action('admin_init','_maby_update_core');

//移除后台插件更新检查
remove_ action( 'load-plugins.php', 'wp_update_plugins');
remove_ action( 'load-update.php', 'wp_update_plugins');
remove_ action( 'load-update-core.php', 'wp_update_plugins');
remove_ action('admin_init','_maybe_update_plugins');

//移除后台主题更新检查
remove_ action( 'load-themes.php','wp_update_themes');
remove_ action( 'load-update.php','wp_update_themes');
remove_ action( 'load-update-core.php', 'wp_update_themes');
remove_ action( 'admin_init','_maybe_update_themes');

//移除不必要的信息,如WordPress版本
remove_action('wp_head', 'feed_links', 2);  //移除feed
remove_action('wp_head', 'feed_links_extra', 3);  //移除feed
remove_action('wp_head', 'rest_output_link_wp_head', 10);
remove_action('wp_head', 'rsd_link');  //移除离线编辑器开放接口
remove_action('wp_head', 'wlwmanifest_link');  //移除离线编辑器开放接口
remove_action('wp_head', 'index_rel_link');  //去除本页唯一链接信息
remove_action('wp_head', 'parent_post_rel_link', 10, 0);  //清除前后文信息
remove_action('wp_head', 'start_post_rel_link', 10, 0);  //清除前后文信息
remove_action('wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
remove_action('wp_head', 'locale_stylesheet');
remove_action('publish_future_post','check_and_publish_future_post',10, 1);
remove_action('wp_head', 'noindex', 1);
remove_action('wp_head', 'wp_print_styles', 8);  //载入css
remove_action('wp_head', 'wp_print_head_scripts', 9);
remove_action('wp_head', 'print_emoji_detection_script', 7);
remove_action('wp_head', 'wp_generator');  //移除WordPress版本
remove_action('wp_head', 'rel_canonical');
remove_action('wp_footer', 'wp_print_footer_scripts');
remove_action('wp_head', 'wp_shortlink_wp_head', 10, 0);
remove_action('template_redirect', 'wp_shortlink_header', 11, 0);
add_action('widgets_init', 'my_remove_recent_comments_style');
function my_remove_recent_comments_style() {
    global $wp_widget_factory;
    remove_action('wp_head', array($wp_widget_factory->widgets['WP_Widget_Recent_Comments'] ,'recent_comments_style'));
}

//评论框禁止HTML
add_filter('pre_comment_content', 'wp_specialchars');

//停用链接猜测
add_filter('redirect_canonical', 'stop_guessing');
function stop_guessing($url) {
    if (is_404()) {
        return false;
    }
    return $url;
}

//禁止自动保存
remove_filter('the_content', 'wptexturize');
remove_action('pre_post_update', 'wp_save_post_revision');
add_action('wp_print_scripts', 'disable_autosave');
function disable_autosave() {
    wp_deregister_script('autosave');
}

//禁用wp-embed.min.js
function disable_embeds_init() {
    /* @var WP $wp */
    global $wp;

    // Remove the embed query var.
    $wp->public_query_vars = array_diff( $wp->public_query_vars, array(
        'embed',
    ) );

    // Remove the REST API endpoint.
    remove_action( 'rest_api_init', 'wp_oembed_register_route' );

    // Turn off
    add_filter( 'embed_oembed_discover', '__return_false' );

    // Don't filter oEmbed results.
    remove_filter( 'oembed_dataparse', 'wp_filter_oembed_result', 10 );

    // Remove oEmbed discovery links.
    remove_action( 'wp_head', 'wp_oembed_add_discovery_links' );

    // Remove oEmbed-specific JavaScript from the front-end and back-end.
    remove_action( 'wp_head', 'wp_oembed_add_host_js' );
    add_filter( 'tiny_mce_plugins', 'disable_embeds_tiny_mce_plugin' );

    // Remove all embeds rewrite rules.
    add_filter( 'rewrite_rules_array', 'disable_embeds_rewrites' );
}

add_action( 'init', 'disable_embeds_init', 9999 );

/**
 * Removes the 'wpembed' TinyMCE plugin.
 *
 * @since 1.0.0
 *
 * @param array $plugins List of TinyMCE plugins.
 * @return array The modified list.
 */
function disable_embeds_tiny_mce_plugin( $plugins ) {
    return array_diff( $plugins, array( 'wpembed' ) );
}

/**
 * Remove all rewrite rules related to embeds.
 *
 * @since 1.2.0
 *
 * @param array $rules WordPress rewrite rules.
 * @return array Rewrite rules without embeds rules.
 */
function disable_embeds_rewrites( $rules ) {
    foreach ( $rules as $rule => $rewrite ) {
        if ( false !== strpos( $rewrite, 'embed=true' ) ) {
            unset( $rules[ $rule ] );
        }
    }

    return $rules;
}

//Remove embeds rewrite rules on plugin activation.
function disable_embeds_remove_rewrite_rules() {
    add_filter( 'rewrite_rules_array', 'disable_embeds_rewrites' );
    flush_rewrite_rules();
}
register_activation_hook( __FILE__, 'disable_embeds_remove_rewrite_rules' );

动静分离

  • 将 CSS / JS / 图片 等静态文件放在 CDN,可以降低源站负载,提高加载速度
  • 博客图片使用 webp 格式,推荐图床工具 PicX,图片托管在 Github 上

CDN 推荐

插件优化

插件主题选择原则

WordPress 拥有大量的优秀的的主题与插件,选择插件时应该遵循几个原则:

  • 只选有用的插件:用处不大的插件只会拖慢博客的运行速度,不需要的插件在后台禁用或删除。
  • 尽量选择正版插件,不要使用未知来源的插件
  • 同类插件不需要安装多个
  • 对于主题,也是相同的道理。如果没有必要,尽量不要使用国外的主题,因为它们可能会引用大量国外的静态资源,拖慢加载速度。国内的主题对于相应文件都会有一定优化,提升加载速度。

缓存优化插件

WordPress 有多种缓存机制,合理使用缓存,能让站点速度大大提升。

  • 使用 WP Rocket / WP Super Cache 等缓存插件
  • 启用 Memcached / Redis 等配合相关 Object Cache

Redis Object Cache

– 官网地址:https://wordpress.org/plugins/redis-cache/

Configuration constant Default Description
WP_REDIS_HOST 127.0.0.1 The hostname of the Redis server
WP_REDIS_PORT 6379 The port of the Redis server
WP_REDIS_PATH The path to the unix socket of the Redis server
WP_REDIS_SCHEME tcp The scheme used to connect: tcp or unix
WP_REDIS_DATABASE 0 The database used by the cache: 0-15
WP_REDIS_PREFIX The prefix used for all cache keys to avoid data collisions, replaces WP_CACHE_KEY_SALT. Should be human readable, not a "salt".
WP_REDIS_PASSWORD The password of the Redis server. Supports Redis ACLs arrays: ['user', 'password']
WP_REDIS_MAXTTL 0 The maximum time-to-live of cache keys
WP_REDIS_CLIENT The client used to communicate with Redis: predis, phpredis or relay
WP_REDIS_TIMEOUT 1 The connection timeout in seconds
WP_REDIS_READ_TIMEOUT 1 The timeout in seconds when reading/writing
WP_REDIS_IGNORED_GROUPS [] Groups that should not be cached between requests in Redis
  • 高级配置选项
Configuration constant Default Description
WP_CACHE_KEY_SALT Deprecated. Replaced by WP_REDIS_PREFIX
WP_REDIS_RETRY_INTERVAL The number of milliseconds between retries
WP_REDIS_GLOBAL_GROUPS [] Additional groups that are considered global on multisite networks
WP_REDIS_METRICS_MAX_TIME 3600 The maximum number of seconds metrics should be stored
WP_REDIS_IGBINARY false Whether to use the igbinary PHP extension for serialization
WP_REDIS_DISABLED false Emergency switch to bypass the object cache without deleting the drop-in
WP_REDIS_DISABLE_ADMINBAR false Disables admin bar display
WP_REDIS_DISABLE_METRICS false Disables metrics collection and display
WP_REDIS_DISABLE_BANNERS false Disables promotional banners
WP_REDIS_DISABLE_DROPIN_AUTOUPDATE false Disables the drop-in auto-update
WP_REDIS_SSL_CONTEXT [] TLS connection options for tls or rediss scheme

手动安装

编辑 wp-config.php,在 define( 'DB_COLLATE', ''); 后添加如下内容

/** Redis Object Cache */
define('WP_REDIS_HOST', '127.0.0.1');
define('WP_REDIS_DATABASE', '0');

Docker Compose 安装

docker-compose.yml 文件

version: '3.0'

services:
  db:
    image: mysql:5.7 # arm架构的机器请将mysql:5.7改为mysql:oracle
    # container_name: wordpress-db
    restart: unless-stopped
    # command: --max-binlog-size=200M --expire-logs-days=2 # 使用mysql 8.0的小伙伴建议使用
    environment:
      MYSQL_ROOT_PASSWORD: rootpassword # 按需修改
      MYSQL_DATABASE: wordpress
      MYSQL_USER: wordpress
      MYSQL_PASSWORD: yourpassword # 按需修改
    volumes:
      - './db:/var/lib/mysql'
    networks:
      - default

  app:
    image: wordpress:latest
    # container_name: wordpress-app
    restart: unless-stopped
    ports:
      - 4145:80  # 按需修改。与防火墙开放端口一致。
    environment:
      WORDPRESS_DB_HOST: db
      WORDPRESS_DB_NAME: wordpress
      WORDPRESS_DB_USER: wordpress
      WORDPRESS_DB_PASSWORD: yourpassword # 按需修改
    volumes:
      - './app:/var/www/html'
    links:
      - db:db
    depends_on:
      - redis
      - db
    networks:
      - default

  redis:
    image: redis:alpine
    # container_name: wordpress-redis
    restart: unless-stopped
    volumes:
      - ./redis-data:/data
    networks:
      - default

networks:
  default:
    name: wordpress

编辑 wp-config.php,在 define( 'DB_COLLATE', ''); 后添加如下内容

/** Redis Object Cache */
define('WP_REDIS_HOST', 'redis');
define('WP_REDIS_DATABASE', '0');

最后将 object-cache.php 这个文件从目录 /wp-content/plugins/redis-cache/includes/ 复制到 wp-content 下。


持续更新中

参考文献

【END】

版权归属: E家之长
本文链接: https://www.5iehome.cc/archives/wordpress-optimization-summary.html
许可协议: 本文使用《署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)》协议授权
暂无评论

发送评论 编辑评论


上一篇
下一篇