0

How would I use a blog/site id to count posts from the id specified site much like wp_count_posts() does for the current site?

I'm trying to create a function for an AJAX accessed endpoint where a user can select a site from a select element to see how many posts there are on other sites.

I really want to stay away from querying the database directly.

2

In order to use wp_count_posts() as you would on a single site, pass the blog id into the switch_to_blog() function before calling wp_count_posts().

Example:

function wpse_get_post_count( $blog_id ){
    switch_to_blog( $blog_id );
    $post_count = wp_count_posts();
    restore_current_blog();
    return $post_count;
}

Ensure restore_current_blog() is used after every switch_to_blog() or you will risk difficulties mentioned in the notes section of the documentation and this WordPress Stack Exchange answer.

  • Don't you need to restore_current_blog() after you switch? So maybe store the value in a variable and then return it after you restore the current blog. – Nikolay Feb 18 '18 at 6:48
  • @Nikolay There doesn't seem to be a reason to restore the "current" blog in this case, but once/if I find one, I will update my answer. – ExcellentSP Feb 18 '18 at 6:55
  • 1
    It says here in the notes section that "restore_current_blog() should be called after every switch_to_blog()": codex.wordpress.org/Function_Reference/restore_current_blog – Nikolay Feb 18 '18 at 9:11
  • Thank you for that @Nikolay, I have edited my answer. – ExcellentSP Feb 18 '18 at 16:57
  • Cool, no problem :) – Nikolay Feb 18 '18 at 17:45

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.