[wp-trac] [WordPress Trac] #16558: switch_to_blog does not properly update global $wpdb
WordPress Trac
wp-trac at lists.automattic.com
Mon Feb 14 22:13:50 UTC 2011
#16558: switch_to_blog does not properly update global $wpdb
--------------------------+-----------------------------
Reporter: divinegod | Owner:
Type: defect (bug) | Status: new
Priority: normal | Milestone: Awaiting Review
Component: General | Version: 3.0.4
Severity: normal | Keywords:
--------------------------+-----------------------------
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
}
}}}
--
Ticket URL: <http://core.trac.wordpress.org/ticket/16558>
WordPress Trac <http://core.trac.wordpress.org/>
WordPress blogging software
More information about the wp-trac
mailing list