0

I am writing a very small cache plugin called Tiny Cache. It would cache only the_content() calls which take - I think - the longest time to generate during a page load.

I am able to hook the_content and store it in the object cache.

How can this plugin serve cached content? How to stop the_content filter from being processed?

remove_all_filters() would destroy all further the_content() calls. Maybe a way to stash filters away and restore them later?

Thank you.

0

The first implementation is in a new function called the_content_cached.

function the_content_cached( $more_link_text = null, $strip_teaser = false ) {

    $post_id = get_the_ID();
    // Not possible to tie content to post ID
    if ( ! $post_id ) {
        the_content( $more_link_text, $strip_teaser );
        return;
    }

    $cached = wp_cache_get( $post_id, 'the_content' );
    // Cache miss
    if ( ! $cached ) {
        add_filter( 'the_content', 'tiny_cache_save_the_content', PHP_INT_MAX );
        the_content( $more_link_text, $strip_teaser );
        remove_filter( 'the_content', 'tiny_cache_save_the_content', PHP_INT_MAX );
        return;
    }

    // Cache hit
    $timestamp = gmdate( 'c' );
    $message_tpl = '<!-- Cached content generated by Tiny cache on %s -->';
    print $cached;
    printf( $message_tpl, $timestamp );
}

// Save the content to the object cache
function tiny_cache_save_the_content( $content ) {

    $post_id = get_the_ID();
    // Tie content to post ID
    if ( $post_id ) {
        wp_cache_set( $post_id, $content, 'the_content' );
    }

    return $content;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.