Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.