Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Trying to iterate through a list of the sites and I can't seem to get set_blog_id working. Here's the sample output:

Array ( [0] => stdClass Object ( [blog_id] => 2 ) [1] => stdClass Object ( [blog_id] => 3 ) [2] => stdClass Object ( [blog_id] => 5 ) )

get new_blog_id from array and check value - blog_id= 2

current_blog= 5

use set_blog_id to set current blog_id to new_blog_id

after set_blog_id, get_current_blog_id= 5 - should be 2

after resetting to oldblog get_current_blog_id 5

As you can see, everything is working but the set_blog_id. Here's the code. Any help would be appreciated!

function return_blog_first_posts(){
global $wpdb;

$site_blog_ids = $wpdb->get_results($wpdb->prepare("SELECT blog_id FROM wp_blogs where blog_id > 1")); /* get all subsite blog ids */
print_r($site_blog_ids); /*output check - "Array ( [0] => stdClass Object ( [blog_id] => 2 ) [1] => stdClass Object ( [blog_id] => 3 ) [2] => stdClass Object ( [blog_id] => 5 ) ) "
echo "</br>"; */

foreach( $site_blog_ids as $blog_id ) { /* iterate through the ids */
print_r( "</br>new blog_id check - blog_id= ".$blog_id->blog_id ); /* output check - this shows blog id */

echo "</br>current_blog= ".get_current_blog_id();
$newblogid = $blog_id->blog_id; //
$oldblog = $wpdb->set_blog_id( $newblogid ); // this is not working
echo "</br> after set_blog_id, get_current_blog_id= ".get_current_blog_id();
}
/* Tell the $wpdb object to go back to using the current site */
$wpdb->set_blog_id( $oldblog );
echo "</br> after resetting to oldblog get_current_blog_id ".get_current_blog_id();
}
return_blog_first_posts();
share|improve this question
add comment

1 Answer

up vote 0 down vote accepted

Use switch_to_blog( $new_blog_id ) instead.

You can find the function in wp-includes/ms-blogs.php.

Update

$wpdb->set_blog_id() doesn’t change the global variable $blog_id which is returned by get_current_blog_id(). switch_to_blog() does change the global variable.

share|improve this answer
    
thanks, unfortunately according to what I've read, switch_to_blog seems to have reliability and performance issues, so the wpdb->set_blog_id method is recommended. Please let me know if you have any ideas as to why my implementation isn't working. –  Dains Feb 16 '12 at 13:46
    
I added an explanation to show why your code doesn’t work. –  toscho Feb 16 '12 at 14:01
    
Thanks for the explanation Toscho. Sorry for the late reply, RL issues + got a new developer for the site. –  Dains Feb 21 '12 at 2:04
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.