#16558 closed defect (bug) (invalid)
switch_to_blog does not properly update global $wpdb
| Reported by: |
|
Owned by: | |
|---|---|---|---|
| Milestone: | Priority: | normal | |
| Severity: | normal | Version: | 3.0.4 |
| Component: | General | Keywords: | worksforme reporter-feedback |
| Focuses: | Cc: |
Description
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
}
Unable to reproduce on trunk. Doesn't look like wpdb.php has really changed since 3.0 though.
Test code:
function switchblog() { global $wpdb; foreach ( $wpdb->get_col("SELECT blog_id FROM $wpdb->blogs") as $blog_id ) { switch_to_blog( $blog_id ); echo "<strong>Blog ID:</strong> $blog_id<br />"; foreach ( $wpdb->tables( 'blog' ) as $table => $value ) { echo "$table: $value<br />"; } echo '<p> </p>'; } die(); } add_action('init', 'switchblog');