# Cache Slow Shortcodes With a Wrapper Shortcode

> Adds a [cached] shortcode you wrap around any slow shortcode or content, such as [cached ttl="3600"][some_feed][/cached]; its output is stored for the time you choose and served from cache after that.

- Type: PHP
- Runs: Run everywhere
- Category: [Performance](https://wpide.com/library/category/performance/)
- Tags: shortcode, cache, transients
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/perf-cached-shortcode/

## Code

```php
add_shortcode( 'cached', function ( $atts, $content = '' ) {
    $atts = shortcode_atts( array( 'ttl' => HOUR_IN_SECONDS, 'key' => '' ), $atts, 'cached' );

    if ( '' === trim( (string) $content ) ) {
        return '';
    }

    $post_id = get_the_ID() ? get_the_ID() : 0;
    $key     = 'wpide_sc_' . md5( $post_id . '|' . $atts['key'] . '|' . $content . '|' . determine_locale() );
    $html    = get_transient( $key );

    if ( false === $html ) {
        $html = do_shortcode( $content );
        set_transient( $key, $html, max( 60, (int) $atts['ttl'] ) );

        if ( $post_id ) {
            $keys   = (array) get_post_meta( $post_id, '_wpide_cached_keys', true );
            $keys[] = $key;
            update_post_meta( $post_id, '_wpide_cached_keys', array_values( array_unique( array_filter( $keys ) ) ) );
        }
    }

    return $html;
} );

add_action( 'save_post', function ( $post_id ) {
    foreach ( (array) get_post_meta( $post_id, '_wpide_cached_keys', true ) as $key ) {
        if ( $key ) {
            delete_transient( $key );
        }
    }
    delete_post_meta( $post_id, '_wpide_cached_keys' );
} );
```

## Notes

Do not wrap content that differs per visitor (cart, account, forms with nonces); the cache is cleared whenever the post is updated.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Cache Slow Shortcodes With a Wrapper Shortcode" 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/
