# Cache Any Expensive Result With One Function

> Adds a wpide_remember() helper that returns a cached value if there is one, or runs your function, stores the result for a set time and returns it, which makes caching slow queries and API calls a one-liner.

- Type: PHP
- Runs: Run everywhere
- Category: [Developer](https://wpide.com/library/category/developer/)
- Tags: caching, transients, helper
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/dev-remember-cache-helper/

## Code

```php
if ( ! function_exists( 'wpide_remember' ) ) {
    function wpide_remember( $key, $seconds, callable $callback ) {
        $cache_key = 'wpide_rmb_' . md5( $key );
        $cached    = get_transient( $cache_key );

        // Wrapped so that false and empty results are cached too.
        if ( is_array( $cached ) && array_key_exists( 'value', $cached ) ) {
            return $cached['value'];
        }

        $value = call_user_func( $callback );
        if ( ! is_wp_error( $value ) ) {
            set_transient( $cache_key, array( 'value' => $value ), max( 1, (int) $seconds ) );
        }

        return $value;
    }

    function wpide_forget( $key ) {
        return delete_transient( 'wpide_rmb_' . md5( $key ) );
    }
}
```

## Notes

Example $top = wpide_remember( 'top_posts', HOUR_IN_SECONDS, function () { return get_posts( ... ); } ); call wpide_forget( 'top_posts' ) to clear it.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Cache Any Expensive Result With One Function" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
