WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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)
        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!

share|improve this question
up vote 5 down vote accepted

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().

share|improve this answer
Amazing! Never saw this function before!! ;) Thanks a lot! – Philipp Jun 10 '13 at 10:50

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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