0

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();

1 Answer 1

0

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.

3
  • 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, 2012 at 13:46
  • I added an explanation to show why your code doesn’t work.
    – fuxia
    Feb 16, 2012 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, 2012 at 2:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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