wordpress 写一款缓存插件
时间: 2023-06-28 19:09:03 浏览: 68
好的,下面是一个简单的WordPress缓存插件示例:
```php
<?php
/**
* Plugin Name: Simple Cache
* Description: A simple caching plugin for WordPress.
* Version: 1.0
* Author: Your Name
* Author URI: https://yourwebsite.com/
*/
// Define cache duration in seconds
define( 'SIMPLE_CACHE_DURATION', 3600 );
// Enable caching for logged-in users
define( 'SIMPLE_CACHE_LOGGED_IN', true );
// Check if page is cacheable
function is_cacheable() {
if ( is_admin() ) {
return false;
}
if ( SIMPLE_CACHE_LOGGED_IN && is_user_logged_in() ) {
return false;
}
return true;
}
// Get cache key
function get_cache_key() {
global $wp;
$url = home_url( $wp->request );
return 'simple_cache_' . md5( $url );
}
// Get cached content
function get_cached_content() {
$key = get_cache_key();
$content = get_transient( $key );
if ( $content ) {
return $content;
}
return false;
}
// Cache content
function cache_content( $content ) {
$key = get_cache_key();
set_transient( $key, $content, SIMPLE_CACHE_DURATION );
return $content;
}
// Filter content before output
function filter_content( $content ) {
if ( is_cacheable() ) {
$cached_content = get_cached_content();
if ( $cached_content !== false ) {
return $cached_content;
}
$content = cache_content( $content );
}
return $content;
}
add_filter( 'the_content', 'filter_content' );
```
这个插件会将页面缓存起来,以便下一次访问时可以更快地加载页面。缓存持续时间可以通过 `SIMPLE_CACHE_DURATION` 常量来设置。如果你想让已登录用户也可以使用缓存,可以将 `SIMPLE_CACHE_LOGGED_IN` 常量设置为 `true`。