• Stars
    star
    144
  • Rank 255,590 (Top 6 %)
  • Language
    PHP
  • License
    MIT License
  • Created almost 7 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Helper for the WordPress object cache and transients.

WP Cache Remember

Build Status Coverage Status GitHub release

WP Cache Remember is a simple WordPress include to introduce convenient new caching functions.

Well-built WordPress plugins know when to take advantage of the object cache and/or transients, but they often end up with code that looks like this:

function do_something() {
    $cache_key = 'some-cache-key';
    $cached    = wp_cache_get( $cache_key );

    // Return the cached value.
    if ( $cached ) {
        return $cached;
    }

    // Do all the work to calculate the value.
    $value = a_whole_lotta_processing();

    // Cache the value.
    wp_cache_set( $cache_key, $value );

    return $value;
}

That pattern works well, but there's a lot of repeated code. This package draws inspiration from Laravel's Cache::remember() method; using wp_cache_remember(), the same code from above becomes:

function do_something() {
    return wp_cache_remember( 'some-cache-key', function () {
        return a_whole_lotta_processing();
    } );
}

Installation

The best way to install this package is via Composer:

$ composer require stevegrunwell/wp-cache-remember

The package ships with the composer/installers package, enabling you to control where you'd like the package to be installed. For example, if you're using WP Cache Remember in a WordPress plugin, you might store the file in an includes/ directory. To accomplish this, add the following to your plugin's composer.json file:

{
    "extra": {
        "installer-paths": {
            "includes/{$name}/": ["stevegrunwell/wp-cache-remember"]
        }
    }
}

Then, from within your plugin, simply include or require the file:

require_once __DIR__ . '/includes/wp-cache-remember/wp-cache-remember.php';

Using as a plugin

If you'd prefer, the package also includes the necessary file headers to be used as a WordPress plugin.

After downloading or cloning the package, move wp-cache-remember.php into either your wp-content/mu-plugins/ (preferred) or wp-content/plugins/ directory. If you chose the regular plugins directory, you'll need to activate the plugin manually via the Plugins › Installed Plugins page within WP Admin.

Bundling within a plugin or theme

WP Cache Remember has been built in a way that it can be easily bundled within a WordPress plugin or theme, even commercially.

Each function declaration is wrapped in appropriate function_exists() checks, ensuring that multiple copies of the library can co-exist in the same WordPress environment.

Usage

WP Cache Remember provides the following functions for WordPress:

Each function checks the response of the callback for a WP_Error object, ensuring you're not caching temporary errors for long periods of time. PHP Exceptions will also not be cached.

wp_cache_remember()

Retrieve a value from the object cache. If it doesn't exist, run the $callback to generate and cache the value.

Parameters

(string) $key
The cache key.
(callable) $callback
The callback used to generate and cache the value.
(string) $group
Optional. The cache group. Default is empty.
(int) $expire
Optional. The number of seconds before the cache entry should expire. Default is 0 (as long as possible).

Example

function get_latest_posts() {
    return wp_cache_remember( 'latest_posts', function () {
        return new WP_Query( array(
            'posts_per_page' => 5,
            'orderby'        => 'post_date',
            'order'          => 'desc',
        ) );
    }, 'my-cache-group', HOUR_IN_SECONDS );
}

wp_cache_forget()

Retrieve and subsequently delete a value from the object cache.

Parameters

(string) $key
The cache key.
(string) $group
Optional. The cache group. Default is empty.
(mixed) $default
Optional. The default value to return if the given key doesn't exist in the object cache. Default is null.

Example

function show_error_message() {
    $error_message = wp_cache_forget( 'form_errors', 'my-cache-group', false );

    if ( $error_message ) {
        echo 'An error occurred: ' . $error_message;
    }
}

remember_transient()

Retrieve a value from transients. If it doesn't exist, run the $callback to generate and cache the value.

Parameters

(string) $key
The cache key.
(callable) $callback
The callback used to generate and cache the value.
(int) $expire
Optional. The number of seconds before the cache entry should expire. Default is 0 (as long as possible).

Example

function get_tweets() {
    $user_id = get_current_user_id();
    $key     = 'latest_tweets_' . $user_id;

    return remember_transient( $key, function () use ( $user_id ) {
        return get_latest_tweets_for_user( $user_id );
    }, 15 * MINUTE_IN_SECONDS );
}

forget_transient()

Retrieve and subsequently delete a value from the transient cache.

Parameters

(string) $key
The cache key.
(mixed) $default
Optional. The default value to return if the given key doesn't exist in transients. Default is null.

remember_site_transient()

Retrieve a value from site transients. If it doesn't exist, run the $callback to generate and cache the value.

This function shares arguments and behavior with remember_transient(), but works network-wide when using WordPress Multisite.

forget_site_transient()

Retrieve and subsequently delete a value from the site transient cache.

This function shares arguments and behavior with forget_transient(), but works network-wide when using WordPress Multisite.

License

Copyright 2018 Steve Grunwell

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

More Repositories

1

asimov

Automatically exclude development dependencies from Apple Time Machine backups
PHP
1,598
star
2

wp-enforcer

Git hooks to encourage well-written WordPress.
Shell
112
star
3

one-time-callbacks

Enable WordPress actions and filter callbacks to be called exactly once.
PHP
65
star
4

schemify

Automatically generate Schema.org JSON-LD markup for WordPress content.
PHP
57
star
5

lost-in-translation

Uncover missing translations and localization strings in Laravel applications.
PHP
35
star
6

time-constants

A series of constants designed to make it easier to express time in PHP applications
PHP
25
star
7

wp404

Get in-depth information about the 404 errors that occur on your WordPress site.
PHP
21
star
8

mcavoy

Discover what visitors are searching for on your WordPress site.
PHP
20
star
9

revision-strike

Periodically purge old post revisions via WP Cron.
PHP
17
star
10

wordpress-git

Reveal.js version of my "Keeping WordPress Under [Version] Control with Git" blog post
HTML
17
star
11

advanced-post-excerpt

Replace the default Post Excerpt meta box with a superior editing experience.
PHP
15
star
12

reveal-ga

Add Google Universal Analytics tracking to your reveal.js presentation.
JavaScript
15
star
13

wp-admin-tabbed-settings-pages

A polyfill for Trac #51086, bringing tabbed settings pages into WP-Admin.
PHP
13
star
14

phpunit-markup-assertions

Assertions for PHPUnit to verify the presence or state of elements within markup
PHP
12
star
15

building-for-php-cli

Slides for "Building for the PHP Command Line Interface"
CSS
12
star
16

wp-client-reference

A WordPress plugin designed for agencies to embed client documentation directly into a WordPress site
PHP
10
star
17

php-cli-examples

Examples to accompany "Building for the PHP Command Line Interface"
8
star
18

intro-to-ci-cd

Slides for "Build and Release Confidently with Continuous Integration and Delivery"
CSS
8
star
19

writing-wp-cli-scripts-that-work

Slides for "Writing WP-CLI Commands That Work!"
CSS
8
star
20

wp-password-generator

The WP Password Generator plugin takes the hassle out of creating new WordPress users by generating random, secure passwords with one click.
PHP
7
star
21

wordpress-starter-theme

My WordPress starter theme so I don't have to repeat myself at the beginning of every project.
PHP
5
star
22

intro-to-testing

Slides for "Testing Like You've Never Tested Before (Because You Haven't)"
CSS
5
star
23

wp-encrypted-options

An API for saving encrypted data into the wp_options table. **NOT YET READY FOR PRODUCTION USE!**
PHP
5
star
24

platform-plugin

Slides for "Considerations & Concerns for Platform Plugin Development"
CSS
5
star
25

technical-debt

Slides for "Up to my Eyeballs in Technical Debt!"
CSS
5
star
26

mailto-link-formatter

Composer package for easily generating RFC 6068-compliant mailto: links in your markup.
PHP
5
star
27

vvv-redis

Custom VVV utility to automatically install and configure Redis
Shell
4
star
28

simple-twitter-timeline

A PHP class for reading public Twitter timelines. Designed with "Latest Tweets"-style widgets in mind.
PHP
4
star
29

semver-parser

Library for parsing and manipulating Semantic Versioning ("SemVer") relases
PHP
4
star
30

pupper

A Twitter clone for use in training courses
PHP
3
star
31

stevegrunwell-com-legacy

Source for http://stevegrunwell.com running the Grunwell 2012 theme.
PHP
3
star
32

wp-analysis

A custom PHP_CodeSniffer ruleset and report format to generate user-friendly details about what high-level issues exist and *why* they're important.
PHP
3
star
33

runkit7-installer

Composer package to automate the installation of Runkit7 in development + CI environments
Shell
3
star
34

protecting-yourself-online-irl

Slides for "Protecting Yourself Online & IRL"
CSS
3
star
35

professional-development-professional-developers

Slides for "Professional Development for Professional Developers"
CSS
3
star
36

code-review-for-me-and-you

Slides for "Code Review: For Me & You"
CSS
3
star
37

php-namespaces

Slides for "A Crash-course in PHP Namespaces for WordPress Developers"
CSS
3
star
38

parse-video-metadata

Extract meta data from videos uploaded to the WordPress media gallery.
PHP
2
star
39

stevegrunwell-com

Source for SteveGrunwell.com in 2018 (not yet launched!)
PHP
2
star
40

son-of-clippy

Add "fun" animated characters to your WordPress edit screens!
JavaScript
2
star
41

write-some-docs

Slides for "I'd Like to Write the World Some Docs"
CSS
2
star
42

smee

ABANDONED: Please use https://github.com/BrainMaestro/composer-git-hooks instead! Library for automatically copying Git hooks into a project.
PHP
2
star
43

taking-the-web-offline

Slides for "Taking the Web Offline"
CSS
2
star
44

wordpress-starter-plugin

A quick template to start a new WordPress plugin. Meant to complement https://github.com/stevegrunwell/wordpress-starter-theme
PHP
2
star
45

laravel-authentication-made-easy

Slides for "Laravel Authentication and Permissions Made Easy"
CSS
2
star
46

chronology

PHP
1
star
47

up-and-running-with-wp-cli

Slides for "Up and Running with WP-CLI"
CSS
1
star
48

wp-test-assertions

Additional PHPUnit assertions for testing WordPress plugins and themes.
Shell
1
star
49

mustache-auction

Auction your facial hair style this Movember in the name of men's health!
PHP
1
star
50

grunwell-reveal-theme

CSS overrides for Reveal.js presentations
CSS
1
star
51

wordpress-security-basics

Presentation on WordPress Security Basics based on http://stevegrunwell.com/blog/wordpress-security-basics
CSS
1
star
52

structured-data

Slides for "Computers <3 Structured Data"
CSS
1
star
53

custom-orders-table

Slides for "Custom Tables & the Checkout Bottleneck"
HTML
1
star
54

githookd

Abandoned: Please see https://github.com/BrainMaestro/composer-git-hooks instead. PHP-CLI framework for installing Git Hooks automatically.
PHP
1
star
55

volunteer-line

*Work in Progress* Connecting volunteers of grass-roots campaigns with the community
PHP
1
star
56

laravel-in-a-nutshell

A basic overview of Laravel 5.0 principles for developers new to the framework.
HTML
1
star
57

php-compatibility

Test a package's compatibility with different versions of PHP.
Shell
1
star
58

Barker

A jQuery-powered, Growl-like notification system for in-page news, tweets, and more
JavaScript
1
star