﻿id	summary	reporter	owner	description	type	status	priority	milestone	component	version	severity	resolution	keywords	cc
16558	switch_to_blog does not properly update global $wpdb	divinegod		"when using switch_to_blog in a plugin the global $wpdb is not properly updated. The $wpdb->posts member is not prefixed correctly causing other functions to misbehave.

To make it behave I had to use $wpdb->set_prefix() passing in the result of $wpdb->get_blog_prefix($blog_id), but this sets $wpdb->base_prefix to a new value (instead of ""wp_"". Then subsequent calls to switch_to_blog and fixing the $wpdb->posts again, introduces yet another problem: ""wp_2_3_"" as prefix.
My workaround to this ended up being:

$wpdb->set_prefix($wpdb->set_prefix($wpdb->get_blog_prefix($blog_id)), false);

I use this in a plugin that iterates over every blog in a network setup, getting posts, comments, etc. and caching them in a separate DB.

sort-of-pseudo code:

{{{
function do_stuff() {
  global $wpdb;
  $blogids = $wpdb->get_col($wpdb->prepare(""SELECT blog_id FROM $wpdb->blogs""));
  foreach ($blogids as $blog_id) {
    switch_to_blog($blog_id);
    stuff($blog_id);
  }
}
function stuff($blogid) {
  global $wpdb;
  // $wpdb->posts == ""wp_posts""
  $wpdb->set_prefix($wpdb->set_prefix($wpdb->get_blog_prefix($blog_id)), false);
  // $wpdb->posts == ""wp_$blogid_posts"" if $blogid != 1 or 0
}
}}}"	defect (bug)	closed	normal		General	3.0.4	normal	invalid	worksforme reporter-feedback	
