功能简介
使用 Memcached/Redis 和 Transient 缓存优化 WordPress 自动草稿和媒体库月份加载,提升后台性能。
自动草稿优化
使用 Memcached/Redis 缓存用户最近一次创建的“自动草稿”文章 ID,避免每次新建文章都创建新的自动草稿,提高性能。
媒体库月份缓存优化
使用 Transient 缓存 WordPress 后台媒体库的月份列表,减少数据库查询,提升加载速度。
使用说明
依赖环境
WordPress 已启用 Memcached 支持(例如使用 Memcached 或 Redis 缓存插件)。
若未使用 Memcached,自动草稿部分仍会运行,但不会缓存数据,功能无效。
媒体库优化部分使用 Transient,无需额外配置。
功能开关
插件启用后自动生效,无设置页面。
其他说明
如果你使用的是 Redis,wp_cache_set() 和 wp_cache_get() 依然有效,因为 WordPress 的缓存接口是统一的。
如果你没有使用 Memcached/Redis,建议安装并启用 Redis Object Cache 插件以支持缓存功能。
插件下载安装
<?php
/*
Plugin Name: WPEXP - 缓存增强
Plugin URI: https://www.dujin.org/
Description: 使用 Memcached 和 Transient 缓存优化 WordPress 自动草稿和媒体库月份加载,提升后台性能。
Version: 1.0
Author: dujin.org
Author URI: https://www.dujin.org/
License: GPL2
*/
// 防止直接访问
if (!defined('ABSPATH')) {
exit;
}
/**
* 优化自动草稿(需要 Memcached 扩展支持)
*/
add_action('current_screen', function ($current_screen) {
// 只在新建文章时执行
if ($current_screen->base !== 'post' || $current_screen->post_type === 'attachment' || $current_screen->action !== 'add') {
return;
}
$user_id = get_current_user_id();
$cache_key = 'wpjam_' . $current_screen->post_type . '_last_post_id';
// 检查缓存中是否有自动草稿 ID
if ($last_post_id = wp_cache_get($user_id, $cache_key)) {
$post = get_post($last_post_id);
if ($post && $post->post_status === 'auto-draft') {
wp_redirect(admin_url('post.php?post=' . $last_post_id . '&action=edit'));
exit;
}
}
// 缓存当前自动草稿 ID
add_action('admin_footer', function () use ($cache_key, $user_id) {
global $post;
if (!empty($post->ID)) {
wp_cache_set($user_id, $post->ID, $cache_key, HOUR_IN_SECONDS);
}
});
}, 10, 1);
/**
* 优化媒体库月份列表加载
*/
add_filter('media_library_months_with_files', function ($months) {
$months = get_transient('wpjam_media_library_months');
if ($months === false) {
global $wpdb;
$months = $wpdb->get_results(
"SELECT DISTINCT YEAR(post_date) AS year, MONTH(post_date) AS month " .
"FROM $wpdb->posts " .
"WHERE post_type = 'attachment' " .
"ORDER BY post_date DESC"
);
set_transient('wpjam_media_library_months', $months, WEEK_IN_SECONDS);
}
return $months;
});









