How to cache a shortcode functions output?

I would like to show on my startpage the total count of posts in a WordPress Multisite. Those are nearly 7000 in 500 Blogs. So I made a function which has to go through every blog to count the posts. Of cause that need a lot of time so this function isn’t very useful. But is there a way to say that it should cache the output for let’s say 1 Week?!

Here’s my code:

function posts_count_func( $args ){

    global $wpdb;
    $blogs = $wpdb->get_results( $wpdb->prepare(
            "SELECT * FROM {$wpdb->blogs} WHERE  spam = '0' 
            AND deleted = '0' AND archived = '0' 
            ORDER BY registered DESC, 2", ARRAY_A ) );

    $original_blog_id = get_current_blog_id();

     $args = array(
        'numberposts'     => -1,
        'post_type'       => 'post',
        'post_status'     => 'publish' );
    $total_network = $draft_network = 0;
    $total_sites = 0;

    foreach ($blogs as $blog)
    {
        wp_cache_flush();
        switch_to_blog( $blog->blog_id );
        $args['post_status'] = 'publish';
        if (count(get_posts($args))<2) { continue; }
        $total_posts = count( get_posts( $args ) );
        $total_network += $total_posts;
        $total_sites += 1;

        $args['post_status'] = 'draft';

        }

 return $total_network;

 switch_to_blog( $original_blog_id );
}
add_shortcode( 'posts', 'posts_count_func' );

Thank you so much and have a good time!

1 Answer
1

You might have a look at the WordPress Transient API.

You should be able to store your shortcode output $total_network with

set_transient( 'my_shortcode_cache', $total_network, WEEK_IN_SECONDS );

where WEEK_IN_SECONDS is a built in constant equal to 604800.

You can then fetch it with:

get_transient( 'my_shortcode_cache' );

If you need it to work network wide there exists also set_site_transient() and get_site_transient().

Leave a Comment