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.
Opens WPIDE on
Code
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 add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.