Make WordPress Core

Opened 11 years ago

Closed 11 years ago

Last modified 11 years ago

#16558 closed defect (bug) (invalid)

switch_to_blog does not properly update global $wpdb

Reported by: divinegod Owned by:
Milestone: Priority: normal
Severity: normal Version: 3.0.4
Component: General Keywords: worksforme reporter-feedback
Focuses: Cc:


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

Change History (4)

#1 @kawauso
11 years ago

  • Keywords worksforme added

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 as $table ) {
			$value = $wpdb->$table;
			echo "$table: $value<br />";
		echo '<p>&nbsp;</p>';
add_action('init', 'switchblog');
Last edited 11 years ago by kawauso (previous) (diff)

#2 @kawauso
11 years ago

  • Keywords reporter-feedback added

#3 @divinegod
11 years ago

  • Resolution set to invalid
  • Status changed from new to closed

I've found the error in the code. switch_to_blog() was called with correct argument.

The code I had used $wpdb->get_results instead of $wpdb->get_col

Closing this as invalid.

#4 @nacin
11 years ago

  • Milestone Awaiting Review deleted
Note: See TracTickets for help on using tickets.