-
Notifications
You must be signed in to change notification settings - Fork 3
/
Plugin.php
113 lines (102 loc) · 2.68 KB
/
Plugin.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?php
/*
Plugin Name: Menu Caching
Plugin URI: http://crumbls.com
Description: Very simple menu caching plugin for WordPress. Written for PHP7.
Author: Chase C. Miller
Version: 0.0.1
*/
namespace Crumbls\WordPress\MenuCache;
defined('ABSPATH') || exit(1);
/**
* Class FrontEnd
* @package Crumbls\WordPress\MenuCache
* @description bring front end caching to WordPress menus.
*/
class FrontEnd
{
protected static $instance = false;
/**
* Singleton generator
* @return FrontEnd
*/
public static function getInstance()
{
if (!isset(static::$instance) || !static::$instance) {
static::$instance = new FrontEnd();
static::_init();
}
return static::$instance;
}
/**
* Initialzier for static class.
*/
protected static function _init()
{
$s = get_called_class();
add_filter('pre_wp_nav_menu', $s . '::preNavMenu', -1, 2);
add_filter('wp_nav_menu', $s . '::navMenu', PHP_INT_MAX, 2);
}
/**
* Store any menu as a transient.
* @param $menu
* @param $args
* @return mixed
*/
public static function navMenu($menu, $args)
{
if (static::isCacheable($args)) {
set_transient(static::getKey($args), $menu,
// This filter controls how long to cache a menu for. Default is 5 minutes.
apply_filters('menu_cache_expiration', 300, $args)
);
}
return $menu;
}
/**
* If a menu exists in the cache, return it.
* @param $menu
* @param $args
* @return mixed
*/
public static function preNavMenu($menu, $args)
{
if (static::isCacheable($args)) {
$ret = get_transient(static::getKey($args));
if ($ret !== false) {
return $ret;
}
}
return $menu;
}
/**
* Returns a unique key.
* @return string.
*/
protected static function getKey(&$args)
{
// Set key if needed
if (
!property_exists($args, 'menu_key')
||
!$args->menu_key
) {
$args->menu_key = md5(json_encode($args));
}
return $args->menu_key;
}
/**
* Checks if a menu should be cached.
*
* @param object $args Menu args.
*
* @return bool Whether or not the menu should be cached.
*/
protected static function isCacheable($args)
{
// A simple filter to allow a menu to be excluded.
return (bool)apply_filters('menu_cache_enable', true, $args);
}
}
// If you are using composer to load this, then remove this line.
FrontEnd::getInstance();