WordPress 智能缓存管理

WordPress 智能缓存管理,控制您的 Autoptimize 缓存,同时保持最佳性能。

<?php
/**
* BDFG Autoptimize Cache Manager - Smart cache management for WordPress
*
* A thoughtfully crafted cache management solution by beiduofengou.
* Keeps your Autoptimize cache under control while maintaining optimal performance.
*
* @package BDFGAutoptimizeCache
* @author beiduofengou <[email protected]>
* @copyright 2024 beiduofengou
* @license GPL v2 or later
*
* Plugin Name: BDFG Autoptimize Cache Manager
* Plugin URI: https://beiduofengou.net/2024/06/15/bdfg-autoptimize-cache-manager/
* Description: Intelligently manages your Autoptimize cache based on size or time intervals. Created by beiduofengou.
* Version: 2.1.0
* Requires PHP: 7.2
* Author: beiduofengou
* Author URI: https://beiduofengou.net
* License: GPL v2 or later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Text Domain: bdfg-autocache
* Domain Path: /languages
*/

// Prevent direct access
defined('ABSPATH') || exit('No direct script access allowed');

// Plugin version and paths
define('BDFG_AUTOCACHE_VERSION', '2.1.0');
define('BDFG_AUTOCACHE_FILE', __FILE__);
define('BDFG_AUTOCACHE_PATH', plugin_dir_path(__FILE__));
define('BDFG_AUTOCACHE_URL', plugin_dir_url(__FILE__));
define('BDFG_AUTOCACHE_BASENAME', plugin_basename(__FILE__));

// Require core files
require_once BDFG_AUTOCACHE_PATH . 'includes/class-bdfg-autoptimize-cache-manager.php';
require_once BDFG_AUTOCACHE_PATH . 'includes/class-bdfg-cache-stats.php';
require_once BDFG_AUTOCACHE_PATH . 'includes/class-bdfg-notifications.php';
require_once BDFG_AUTOCACHE_PATH . 'includes/class-bdfg-api.php';

// Load CLI commands if WP-CLI is available
if (defined('WP_CLI') && WP_CLI) {
require_once BDFG_AUTOCACHE_PATH . 'includes/class-bdfg-cli-commands.php';
}

/**
* Begins execution of the plugin.
*
* @since 2.1.0
*/
function bdfg_autoptimize_cache_manager_init() {
// Initialize core components
$manager = BDFG_Autoptimize_Cache_Manager::get_instance();
BDFG_Cache_Stats::get_instance();
BDFG_Notifications::get_instance();
BDFG_Cache_API::get_instance();

return $manager;
}

// Hook into WordPress
add_action('plugins_loaded', 'bdfg_autoptimize_cache_manager_init', 20);

/**
* Plugin activation handler
*/
function bdfg_autocache_activate() {
// Verify dependencies
if (!class_exists('autoptimizeCache')) {
deactivate_plugins(plugin_basename(__FILE__));
wp_die(
__('BDFG Autoptimize Cache Manager requires Autoptimize plugin to be installed and activated.', 'bdfg-autocache'),
'Plugin dependency check',
['back_link' => true]
);
}

// Create necessary database tables and options
$manager = bdfg_autoptimize_cache_manager_init();
$manager->activate();

// Schedule events
if (!wp_next_scheduled('bdfg_autocache_daily_cleanup')) {
wp_schedule_event(time(), 'daily', 'bdfg_autocache_daily_cleanup');
}

// Set activation flag for welcome notice
set_transient('bdfg_autocache_activated', true, 30);
}
register_activation_hook(__FILE__, 'bdfg_autocache_activate');

/**
* Plugin deactivation handler
*/
function bdfg_autocache_deactivate() {
// Clean up scheduled events
wp_clear_scheduled_hook('bdfg_autocache_daily_cleanup');
wp_clear_scheduled_hook('bdfg_autocache_clear_cache');

// Clear any existing notices
delete_transient('bdfg_autocache_activated');
}
register_deactivation_hook(__FILE__, 'bdfg_autocache_deactivate');

/**
* Plugin uninstall handler
*/
function bdfg_autocache_uninstall() {
// Clean up plugin options
delete_option('bdfg_autocache_settings');
delete_option('bdfg_autocache_stats');
delete_option('bdfg_autocache_notification_settings');

// Remove custom capabilities
$role = get_role('administrator');
if ($role) {
$role->remove_cap('manage_bdfg_cache');
}
}
register_uninstall_hook(__FILE__, 'bdfg_autocache_uninstall');

// Add settings link on plugin page
add_filter('plugin_action_links_' . BDFG_AUTOCACHE_BASENAME, 'bdfg_autocache_settings_link');

/**
* Adds settings link to plugin actions
*
* @param array $links Existing plugin action links
* @return array Modified plugin action links
*/
function bdfg_autocache_settings_link($links) {
$settings_link = sprintf(
'<a href="%s">%s</a>',
admin_url('options-general.php?page=bdfg-autocache'),
__('Settings', 'bdfg-autocache')
);
array_unshift($links, $settings_link);
return $links;
}

/**
* Add welcome notice for new installations
*/
function bdfg_autocache_admin_notice() {
if (get_transient('bdfg_autocache_activated')) {
?>
<div class="notice notice-success is-dismissible">
<p>
<?php
printf(
__('Thank you for installing BDFG Autoptimize Cache Manager! Please visit the <a href="%s">settings page</a> to configure the plugin.', 'bdfg-autocache'),
admin_url('options-general.php?page=bdfg-autocache')
);
?>
</p>
</div>
<?php
delete_transient('bdfg_autocache_activated');
}
}
add_action('admin_notices', 'bdfg_autocache_admin_notice');

/**
* Add custom interval for cache clearing
*
* @param array $schedules Existing cron schedules
* @return array Modified cron schedules
*/
function bdfg_autocache_cron_schedules($schedules) {
$schedules['bdfg_fifteen_minutes'] = array(
'interval' => 900,
'display' => __('Every 15 minutes', 'bdfg-autocache')
);
return $schedules;
}
add_filter('cron_schedules', 'bdfg_autocache_cron_schedules');

/**
* Load plugin textdomain
*/
function bdfg_autocache_load_textdomain() {
load_plugin_textdomain(
'bdfg-autocache',
false,
dirname(BDFG_AUTOCACHE_BASENAME) . '/languages/'
);
}
add_action('init', 'bdfg_autocache_load_textdomain');

/**
* Add plugin meta links
*
* @param array $links Existing plugin meta links
* @param string $file Plugin file
* @return array Modified plugin meta links
*/
function bdfg_autocache_plugin_meta($links, $file) {
if ($file === BDFG_AUTOCACHE_BASENAME) {
$links[] = sprintf(
'<a href="%s" target="_blank">%s</a>',
'https://beiduofengou.net/docs/bdfg-autocache/',
__('Documentation', 'bdfg-autocache')
);
$links[] = sprintf(
'<a href="%s" target="_blank">%s</a>',
'https://beiduofengou.net/support/',
__('Support', 'bdfg-autocache')
);
}
return $links;
}
add_filter('plugin_row_meta', 'bdfg_autocache_plugin_meta', 10, 2);

includes/class-bdfg-cache-stats.php

相关文章: WooCommerce 自定义”加入购物车”按钮

<?php
/**
* Cache Statistics Handler
*
* Manages and tracks cache statistics for the BDFG Autoptimize Cache Manager.
*
* @package BDFGAutoptimizeCache
* @subpackage Statistics
* @author beiduofengou <[email protected]>
* @copyright 2024 beiduofengou
* @license GPL v2 or later
*/

class BDFG_Cache_Stats {
/**
* Instance of this class.
*
* @var BDFG_Cache_Stats
*/
private static $instance = null;

/**
* Option name for storing stats
*
* @var string
*/
private $stats_option = 'bdfg_autocache_stats';

/**
* Stats retention period in days
*
* @var int
*/
private $retention_days = 30;

/**
* Get class instance
*
* @return BDFG_Cache_Stats
*/
public static function get_instance() {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}

/**
* Constructor
*/
private function __construct() {
add_action('bdfg_cache_cleared', [$this, 'log_cache_clear'], 10, 2);
add_action('bdfg_autocache_daily_cleanup', [$this, 'cleanup_old_stats']);
}

/**
* Log a cache clear event
*
* @param string $trigger_type What triggered the cache clear
* @param array $metadata Additional data about the clear event
*/
public function log_cache_clear($trigger_type, $metadata = []) {
$stats = get_option($this->stats_option, []);
$start_time = microtime(true);

// Get cache size before clearing
$cache_size_before = $this->get_cache_size_before();

// Record the clear event
$new_entry = [
'timestamp' => time(),
'trigger' => $trigger_type,
'cache_size_before' => $cache_size_before,
'freed_space' => $metadata['freed_space'] ?? $cache_size_before,
'execution_time' => microtime(true) - $start_time,
'metadata' => $metadata
];

array_unshift($stats, $new_entry);

// Keep only recent entries
$stats = array_slice($stats, 0, 100);

update_option($this->stats_option, $stats, false);

do_action('bdfg_cache_stats_updated', $new_entry);
}

/**
* Get a summary of cache statistics
*
* @return array Statistics summary
*/
public function get_stats_summary() {
$stats = get_option($this->stats_option, []);
$total_clears = count($stats);

if ($total_clears === 0) {
return [
'total_clears' => 0,
'avg_size_cleared' => 0,
'avg_execution_time' => 0,
'last_clear' => null,
'total_space_saved' => 0,
'efficiency_score' => 0
];
}

$total_size_cleared = 0;
$total_execution_time = 0;

foreach ($stats as $entry) {
$total_size_cleared += $entry['freed_space'];
$total_execution_time += $entry['execution_time'];
}

// Calculate efficiency score (0-100)
$efficiency_score = min(100, (
($total_size_cleared / $total_clears / (50 * 1024 * 1024)) * 100
));

return [
'total_clears' => $total_clears,
'avg_size_cleared' => $total_size_cleared / $total_clears,
'avg_execution_time' => $total_execution_time / $total_clears,
'last_clear' => $stats[0]['timestamp'],
'total_space_saved' => $total_size_cleared,
'efficiency_score' => round($efficiency_score, 2)
];
}

/**
* Remove old statistics entries
*/
public function cleanup_old_stats() {
$stats = get_option($this->stats_option, []);
$cutoff_time = time() - ($this->retention_days * DAY_IN_SECONDS);

$stats = array_filter($stats, function($entry) use ($cutoff_time) {
return $entry['timestamp'] > $cutoff_time;
});

update_option($this->stats_option, array_values($stats), false);
}

/**
* Get the size of the cache before clearing
*
* @return int Size in bytes
*/
private function get_cache_size_before() {
$cache_dir = WP_CONTENT_DIR . '/cache/autoptimize/';
return $this->calculate_directory_size($cache_dir);
}

/**
* Calculate the total size of a directory
*
* @param string $dir Directory path
* @return int Size in bytes
*/
private function calculate_directory_size($dir) {
if (!is_dir($dir)) {
return 0;
}

$size = 0;
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS)
);

foreach ($files as $file) {
$size += $file->getSize();
}

return $size;
}
}

includes/class-bdfg-notifications.php

<?php
/**
* Notifications Handler
*
* Manages email notifications for the BDFG Autoptimize Cache Manager.
* Created with ❤️ by beiduofengou (https://beiduofengou.net)
*
* @package BDFGAutoptimizeCache
* @subpackage Notifications
* @author beiduofengou <[email protected]>
* @copyright 2024 beiduofengou
* @license GPL v2 or later
*/

class BDFG_Notifications {
/**
* Instance of this class.
*
* @var BDFG_Notifications
*/
private static $instance = null;

/**
* Notification settings
*
* @var array
*/
private $settings;

/**
* Notification cooldown periods (in seconds)
*
* @var array
*/
private $cooldowns = [
'size_warning' => 86400, // 24 hours
'cache_cleared' => 3600 // 1 hour
];

/**
* Get class instance
*
* @return BDFG_Notifications
*/
public static function get_instance() {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}

/**
* Constructor
*/
private function __construct() {
$this->settings = get_option('bdfg_autocache_notification_settings', [
'email_enabled' => false,
'email_recipients' => get_option('admin_email'),
'notification_events' => ['cache_cleared', 'size_warning'],
'size_warning_threshold' => 80, // Percentage
'branding' => true
]);

add_action('bdfg_cache_cleared', [$this, 'handle_cache_cleared_notification'], 10, 2);
add_action('bdfg_autocache_daily_cleanup', [$this, 'check_cache_size_warning']);
}

/**
* Handle cache cleared notification
*
* @param string $trigger The event that triggered the cache clear
* @param array $metadata Additional data about the clear event
*/
public function handle_cache_cleared_notification($trigger, $metadata) {
if (!$this->should_send_notification('cache_cleared')) {
return;
}

$stats = BDFG_Cache_Stats::get_instance()->get_stats_summary();
$freed_space = $metadata['freed_space'] ?? 0;

$subject = sprintf(
'[%s] %s',
get_bloginfo('name'),
__('Cache Cleared Successfully', 'bdfg-autocache')
);

$message = $this->build_email_message(
'cache_cleared',
[
'trigger' => $trigger,
'freed_space' => size_format($freed_space),
'execution_time' => round($metadata['execution_time'] ?? 0, 2),
'total_clears' => $stats['total_clears']
]
);

$this->send_email($subject, $message);
$this->update_notification_timestamp('cache_cleared');
}

/**
* Check if cache size warning should be sent
*/
public function check_cache_size_warning() {
if (!$this->should_send_notification('size_warning')) {
return;
}

$manager = BDFG_Autoptimize_Cache_Manager::get_instance();
$cache_size = $manager->get_cache_size();
$max_size = $manager->get_max_size_bytes();

$usage_percentage = ($cache_size / $max_size) * 100;

if ($usage_percentage >= $this->settings['size_warning_threshold']) {
$this->send_size_warning($usage_percentage, $cache_size, $max_size);
$this->update_notification_timestamp('size_warning');
}
}

/**
* Build email message with consistent branding
*
* @param string $type Message type
* @param array $data Message data
* @return string
*/
private function build_email_message($type, $data) {
$message = '';

// Add header
if ($this->settings['branding']) {
$message .= "🚀 BDFG Autoptimize Cache Manager\n";
$message .= "Created by beiduofengou (https://beiduofengou.net)\n\n";
}

// Add main content
switch ($type) {
case 'cache_cleared':
$message .= sprintf(
__("Hello,\n\nYour website's cache has been automatically cleared:\n\n" .
"• Trigger: %s\n" .
"• Space Freed: %s\n" .
"• Processing Time: %s seconds\n" .
"• Total Cache Clears: %d\n\n",
'bdfg-autocache'),
$data['trigger'],
$data['freed_space'],
$data['execution_time'],
$data['total_clears']
);
break;

case 'size_warning':
$message .= sprintf(
__("Hello,\n\nAttention needed - Cache size alert:\n\n" .
"• Current Usage: %.1f%%\n" .
"• Current Size: %s\n" .
"• Maximum Size: %s\n" .
"• Warning Threshold: %d%%\n\n" .
"Recommended Action: Consider reviewing your cache settings or schedule an automatic cleanup.\n\n",
'bdfg-autocache'),
$data['usage'],
$data['current_size'],
$data['max_size'],
$data['threshold']
);
break;
}

// Add footer
$message .= __("Best regards,\nBDFG Cache Manager\n", 'bdfg-autocache');

if ($this->settings['branding']) {
$message .= "\n--\n";
$message .= __("Need help? Visit our support center: https://beiduofengou.net/support", 'bdfg-autocache');
}

return $message;
}

/**
* Send size warning notification
*
* @param float $usage_percentage Current cache usage percentage
* @param int $current_size Current cache size in bytes
* @param int $max_size Maximum allowed cache size in bytes
*/
private function send_size_warning($usage_percentage, $current_size, $max_size) {
$subject = sprintf(
'[%s] %s',
get_bloginfo('name'),
__('Cache Size Warning', 'bdfg-autocache')
);

$message = $this->build_email_message('size_warning', [
'usage' => $usage_percentage,
'current_size' => size_format($current_size),
'max_size' => size_format($max_size),
'threshold' => $this->settings['size_warning_threshold']
]);

$this->send_email($subject, $message);
}

/**
* Send email to configured recipients
*
* @param string $subject Email subject
* @param string $message Email message
* @return bool Whether the email was sent successfully
*/
private function send_email($subject, $message) {
if (!$this->settings['email_enabled']) {
return false;
}

$headers = [
'Content-Type: text/plain; charset=UTF-8',
'From: ' . get_bloginfo('name') . ' <' . get_option('admin_email') . '>',
'X-BDFG-Cache-Manager: v' . BDFG_AUTOCACHE_VERSION
];

$recipients = array_map('trim', explode(',', $this->settings['email_recipients']));
$success = true;

foreach ($recipients as $recipient) {
if (!empty($recipient)) {
$result = wp_mail($recipient, $subject, $message, $headers);
$success = $success && $result;
}
}

return $success;
}

/**
* Check if notification should be sent based on cooldown
*
* @param string $type Notification type
* @return bool
*/
private function should_send_notification($type) {
if (!$this->settings['email_enabled'] ||
!in_array($type, $this->settings['notification_events'])) {
return false;
}

$last_sent = get_option('bdfg_autocache_last_' . $type . '_notification', 0);
$cooldown = $this->cooldowns[$type] ?? 3600;

return (time() - $last_sent) >= $cooldown;
}

/**
* Update last notification timestamp
*
* @param string $type Notification type
*/
private function update_notification_timestamp($type) {
update_option('bdfg_autocache_last_' . $type . '_notification', time(), false);
}
}

includes/class-bdfg-cli-commands.php

相关文章: WordPress 地图定位插件

<?php
/**
* WP-CLI Commands for BDFG Autoptimize Cache Manager
*
* Provides command-line interface functionality for cache management.
* Created by beiduofengou (https://beiduofengou.net)
*
* @package BDFGAutoptimizeCache
* @subpackage CLI
* @author beiduofengou <[email protected]>
* @copyright 2024 beiduofengou
* @license GPL v2 or later
*/

if (defined('WP_CLI') && WP_CLI) {

class BDFG_CLI_Commands extends WP_CLI_Command {
/**
* Manage Autoptimize cache through command line.
*
* ## OPTIONS
*
* <action>
* : The action to perform (clear, status, stats)
*
* [--force]
* : Force clear the cache regardless of current settings
*
* [--quiet]
* : Suppress informational messages
*
* ## EXAMPLES
*
* # Clear the cache
* $ wp bdfg-cache clear
*
* # Force clear the cache
* $ wp bdfg-cache clear --force
*
* # Show cache status
* $ wp bdfg-cache status
*
* # Display cache statistics
* $ wp bdfg-cache stats
*
* @when after_wp_load
*/
public function __invoke($args, $assoc_args) {
if (empty($args[0])) {
WP_CLI::error(__('Please specify an action: clear, status, or stats', 'bdfg-autocache'));
return;
}

$action = $args[0];

switch ($action) {
case 'clear':
$this->clear_cache($assoc_args);
break;

case 'status':
$this->show_status($assoc_args);
break;

case 'stats':
$this->show_stats($assoc_args);
break;

default:
WP_CLI::error(sprintf(
__('Unknown action: %s', 'bdfg-autocache'),
$action
));
}
}

/**
* Clear the cache
*
* @param array $args Command arguments
*/
private function clear_cache($args) {
$force = WP_CLI\Utils\get_flag_value($args, 'force', false);
$quiet = WP_CLI\Utils\get_flag_value($args, 'quiet', false);

$manager = BDFG_Autoptimize_Cache_Manager::get_instance();

if (!$quiet) {
WP_CLI::log(__('Checking cache status...', 'bdfg-autocache'));
}

if ($force || $manager->should_clear_cache()) {
$start_time = microtime(true);
$size_before = $manager->get_cache_size();

$manager->clear_cache();

$time_taken = round(microtime(true) - $start_time, 2);

if (!$quiet) {
WP_CLI::success(sprintf(
__('Cache cleared successfully in %s seconds', 'bdfg-autocache'),
$time_taken
));

WP_CLI::log(sprintf(
__('Freed space: %s', 'bdfg-autocache'),
size_format($size_before)
));
}
} else {
WP_CLI::warning(
__('Cache clearing conditions not met. Use --force to clear anyway.', 'bdfg-autocache')
);
}
}

/**
* Show cache status
*
* @param array $args Command arguments
*/
private function show_status($args) {
$manager = BDFG_Autoptimize_Cache_Manager::get_instance();
$current_size = $manager->get_cache_size();
$max_size = $manager->get_max_size_bytes();
$usage_percent = ($current_size / $max_size) * 100;

$status = [
__('Current Size', 'bdfg-autocache') => size_format($current_size),
__('Maximum Size', 'bdfg-autocache') => size_format($max_size),
__('Usage', 'bdfg-autocache') => sprintf('%.1f%%', $usage_percent),
__('Status', 'bdfg-autocache') => $usage_percent >= 80 ? 'Warning' : 'Normal'
];

$formatter = new \WP_CLI\Formatter($args, array_keys($status));
$formatter->display_items([$status]);
}

/**
* Show cache statistics
*
* @param array $args Command arguments
*/
private function show_stats($args) {
$stats = BDFG_Cache_Stats::get_instance()->get_stats_summary();

$formatted_stats = [
__('Total Cache Clears', 'bdfg-autocache') => $stats['total_clears'],
__('Average Size Cleared', 'bdfg-autocache') => size_format($stats['avg_size_cleared']),
__('Average Execution Time', 'bdfg-autocache') => sprintf('%.2f seconds', $stats['avg_execution_time']),
__('Last Cleared', 'bdfg-autocache') => $stats['last_clear'] ?
date('Y-m-d H:i:s', $stats['last_clear']) : 'Never',
__('Efficiency Score', 'bdfg-autocache') => sprintf('%.1f/100', $stats['efficiency_score'])
];

$formatter = new \WP_CLI\Formatter($args, array_keys($formatted_stats));
$formatter->display_items([$formatted_stats]);
}
}

WP_CLI::add_command('bdfg-cache', 'BDFG_CLI_Commands');
}

includes/class-bdfg-api.php

<?php
/**
* REST API Handler
*
* Provides REST API endpoints for the BDFG Autoptimize Cache Manager.
* Built with expertise by beiduofengou (https://beiduofengou.net)
*
* @package BDFGAutoptimizeCache
* @subpackage API
* @author beiduofengou <[email protected]>
* @copyright 2025 beiduofengou
* @license GPL v2 or later
*/

class BDFG_Cache_API {
/**
* Instance of this class
*
* @var BDFG_Cache_API
*/
private static $instance = null;

/**
* API namespace
*
* @var string
*/
private $namespace = 'bdfg-autocache/v1';

/**
* Get class instance
*
* @return BDFG_Cache_API
*/
public static function get_instance() {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}

/**
* Constructor
*/
private function __construct() {
add_action('rest_api_init', [$this, 'register_routes']);
}

/**
* Register API routes
*/
public function register_routes() {
// Get cache status
register_rest_route($this->namespace, '/status', [
'methods' => WP_REST_Server::READABLE,
'callback' => [$this, 'get_cache_status'],
'permission_callback' => [$this, 'check_permissions'],
]);

// Clear cache
register_rest_route($this->namespace, '/clear', [
'methods' => WP_REST_Server::CREATABLE,
'callback' => [$this, 'clear_cache'],
'permission_callback' => [$this, 'check_permissions'],
'args' => [
'force' => [
'type' => 'boolean',
'default' => false,
'description' => __('Force clear the cache regardless of conditions', 'bdfg-autocache'),
],
],
]);

// Get cache statistics
register_rest_route($this->namespace, '/stats', [
'methods' => WP_REST_Server::READABLE,
'callback' => [$this, 'get_cache_stats'],
'permission_callback' => [$this, 'check_permissions'],
]);
}

/**
* Check if user has required permissions
*
* @return bool
*/
public function check_permissions() {
return current_user_can('manage_options');
}

/**
* Get cache status
*
* @param WP_REST_Request $request API request object
* @return WP_REST_Response
*/
public function get_cache_status($request) {
$manager = BDFG_Autoptimize_Cache_Manager::get_instance();
$current_size = $manager->get_cache_size();
$max_size = $manager->get_max_size_bytes();

return rest_ensure_response([
'status' => 'success',
'data' => [
'current_size' => $current_size,
'current_size_formatted' => size_format($current_size),
'max_size' => $max_size,
'max_size_formatted' => size_format($max_size),
'usage_percent' => ($current_size / $max_size) * 100,
'last_cleared' => get_option('bdfg_autocache_last_cleared', 0),
'should_clear' => $manager->should_clear_cache(),
],
]);
}

/**
* Clear the cache
*
* @param WP_REST_Request $request API request object
* @return WP_REST_Response
*/
public function clear_cache($request) {
$force = $request->get_param('force');
$manager = BDFG_Autoptimize_Cache_Manager::get_instance();

if (!$force && !$manager->should_clear_cache()) {
return new WP_Error(
'cache_conditions_not_met',
__('Cache clearing conditions not met', 'bdfg-autocache'),
['status' => 400]
);
}

$size_before = $manager->get_cache_size();
$start_time = microtime(true);

$result = $manager->clear_cache();

if (!$result) {
return new WP_Error(
'cache_clear_failed',
__('Failed to clear cache', 'bdfg-autocache'),
['status' => 500]
);
}

return rest_ensure_response(['status' => 'success',
'data' => [
'execution_time' => round(microtime(true) - $start_time, 2),
'freed_space' => $size_before,
'freed_space_formatted' => size_format($size_before),
'cleared_at' => '2024-06-15 12:48:47',
'cleared_by' => 'beiduofengou',
'trigger' => $force ? 'manual_force' : 'manual',
],
]);
}

/**
* Get cache statistics
*
* @param WP_REST_Request $request API request object
* @return WP_REST_Response
*/
public function get_cache_stats($request) {
$stats = BDFG_Cache_Stats::get_instance()->get_stats_summary();

return rest_ensure_response([
'status' => 'success',
'data' => [
'total_clears' => $stats['total_clears'],
'avg_size_cleared' => $stats['avg_size_cleared'],
'avg_size_cleared_formatted' => size_format($stats['avg_size_cleared']),
'avg_execution_time' => round($stats['avg_execution_time'], 2),
'last_clear' => $stats['last_clear'],
'last_clear_formatted' => $stats['last_clear'] ?
date('Y-m-d H:i:s', $stats['last_clear']) : null,
'efficiency_score' => $stats['efficiency_score'],
'generated_at' => '2024-06-15 12:48:47',
'generated_by' => 'beiduofengou'
],
]);
}
}

assets/js/admin.js

相关文章: WooCommerce 客户分析报告插件

/**
* BDFG Autoptimize Cache Manager - Admin JavaScript
*
* Handles interactive features in the plugin's admin interface.
* Created by beiduofengou (https://beiduofengou.net)
*/

jQuery(document).ready(function($) {
'use strict';

// Cache selectors
const clearBySelect = $('#bdfg_clear_by');
const maxSizeField = $('.bdfg-max-size-field');
const timeIntervalField = $('.bdfg-time-interval-field');
const clearCacheButton = $('#bdfg-clear-cache-now');
const statusIndicator = $('.bdfg-cache-status');

// Toggle fields based on clear method
clearBySelect.on('change', function() {
const selectedMethod = $(this).val();

if (selectedMethod === 'size') {
maxSizeField.show();
timeIntervalField.hide();
} else {
maxSizeField.hide();
timeIntervalField.show();
}
}).trigger('change');

// Handle manual cache clearing
clearCacheButton.on('click', function(e) {
e.preventDefault();

const $button = $(this);
const originalText = $button.text();

$button.prop('disabled', true)
.text(bdfgAutoCache.clearing_text);

$.ajax({
url: bdfgAutoCache.api_url + '/clear',
method: 'POST',
beforeSend: function(xhr) {
xhr.setRequestHeader('X-WP-Nonce', bdfgAutoCache.nonce);
},
data: {
force: true
}
})
.done(function(response) {
statusIndicator.removeClass('warning error')
.addClass('success')
.text(bdfgAutoCache.cleared_text);

updateCacheStats();
})
.fail(function(jqXHR) {
let errorMessage = bdfgAutoCache.error_text;

if (jqXHR.responseJSON && jqXHR.responseJSON.message) {
errorMessage += ': ' + jqXHR.responseJSON.message;
}

statusIndicator.removeClass('success warning')
.addClass('error')
.text(errorMessage);
})
.always(function() {
$button.prop('disabled', false)
.text(originalText);
});
});

// Update cache statistics
function updateCacheStats() {
$.ajax({
url: bdfgAutoCache.api_url + '/stats',
method: 'GET',
beforeSend: function(xhr) {
xhr.setRequestHeader('X-WP-Nonce', bdfgAutoCache.nonce);
}
})
.done(function(response) {
if (response.success && response.data) {
$('.bdfg-stat-total-clears').text(response.data.total_clears);
$('.bdfg-stat-avg-size').text(response.data.avg_size_cleared_formatted);
$('.bdfg-stat-efficiency').text(response.data.efficiency_score + '/100');

if (response.data.last_clear_formatted) {
$('.bdfg-stat-last-clear').text(response.data.last_clear_formatted);
}
}
});
}

// Initialize tooltips
$('.bdfg-help-tooltip').tooltipster({
theme: 'tooltipster-light',
maxWidth: 300,
animation: 'fade',
delay: 200
});

// Check cache status periodically
if (bdfgAutoCache.auto_refresh) {
setInterval(updateCacheStats, 300000); // Every 5 minutes
}
});

assets/css/admin.css

/**
* BDFG Autoptimize Cache Manager - Admin Styles
*
* Styles for the plugin's admin interface.
* Created by beiduofengou (https://beiduofengou.net)
*/

.bdfg-admin-wrap {
max-width: 1200px;
margin: 20px 0;
padding: 20px;
background: #fff;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.bdfg-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 30px;
padding-bottom: 20px;
border-bottom: 1px solid #eee;
}

.bdfg-header h1 {
margin: 0;
color: #23282d;
font-size: 24px;
font-weight: 600;
}

.bdfg-version {
color: #666;
font-size: 13px;
font-weight: normal;
}

.bdfg-stats-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
margin-bottom: 30px;
}

.bdfg-stat-card {
padding: 20px;
background: #f8f9fa;
border-radius: 6px;
border-left: 4px solid #0073aa;
}

.bdfg-stat-card.warning {
border-left-color: #ffb900;
}

.bdfg-stat-card.error {
border-left-color: #dc3232;
}

.bdfg-stat-value {
font-size: 24px;
font-weight: 600;
color: #23282d;
margin: 10px 0;
}

.bdfg-stat-label {
color: #666;
font-size: 14px;
}

.bdfg-control-panel {
background: #f8f9fa;
padding: 20px;
border-radius: 6px;
margin-bottom: 30px;
}

.bdfg-settings-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 20px;
}

.bdfg-field-group {
margin-bottom: 20px;
}

.bdfg-field-group label {
display: block;
margin-bottom: 8px;
font-weight: 600;
}

.bdfg-field-group select,
.bdfg-field-group input[type="number"] {
width: 100%;
max-width: 250px;
}

.bdfg-help-tooltip {
display: inline-block;
margin-left: 5px;
color: #666;
cursor: help;
}

.bdfg-actions {
margin-top: 30px;
padding-top: 20px;
border-top: 1px solid #eee;
}

.bdfg-button {
display: inline-flex;
align-items: center;
padding: 8px 16px;
border-radius: 4px;
border: 1px solid #0073aa;
background: #0073aa;
color: #fff;
text-decoration: none;
font-size: 14px;
cursor: pointer;
transition: all 0.2s ease;
}

.bdfg-button:hover {
background: #006291;
border-color: #006291;
}

.bdfg-button.secondary {
background: #f8f9fa;
border-color: #ccc;
color: #23282d;
}

.bdfg-button.secondary:hover {
background: #f0f0f1;
border-color: #999;
}

.bdfg-button:disabled {
opacity: 0.7;
cursor: not-allowed;
}

.bdfg-notification {
padding: 15px;
margin-bottom: 20px;
border-radius: 4px;
}

.bdfg-notification.success {
background: #ecf7ed;
border: 1px solid #46b450;
color: #2a4b2d;
}

.bdfg-notification.warning {
background: #fff8e5;
border: 1px solid #ffb900;
color: #664c00;
}

.bdfg-notification.error {
background: #fbeaea;
border: 1px solid #dc3232;
color: #8a1f1f;
}

/* Responsive adjustments */
@media screen and (max-width: 782px) {
.bdfg-header {
flex-direction: column;
text-align: center;
}

.bdfg-version {
margin-top: 10px;
}

.bdfg-stats-grid {
grid-template-columns: 1fr;
}

.bdfg-field-group select,
.bdfg-field-group input[type="number"] {
max-width: 100%;
}
}

 

相关文章: Woocommerce强大的购物车管理扩展

Leave a Comment