Reputation: 35
I'm building a directory site and am stuck on getting the foreach to loop through the multisite's blog IDs. As you can see from the comments in the code, the query for the blog IDs is working fine, the print_r checks show that the array is filled, but when the function gets to the first foreach, the loop returns the same result each time, and print_r on site_blog_id within the foreach loop shows it's empty. Setting site_blog_id manually in the loop makes the rest of the code work fine, so it's definitely something with the foreach's processing of the array.
I'm highly puzzled because this seems identical to many examples of array-foreach code I've seen on the developer's site, including the ones on the query docs page. I'm wondering if I need to do something with the site_blog_ids variable holding the array to make it work with the foreach, but frankly I'm stuck. Any help will be greatly appreciated! David
/* get all subsite blog ids */
global $wpdb;
$site_blog_ids = $wpdb->get_results($wpdb->prepare("SELECT blog_id FROM wp_blogs where blog_id > 1"));
print_r( $site_blog_ids );
/* check output - shows "Array ( [0] => stdClass Object ( [blog_id] => 2 ) [1] => stdClass Object ( [blog_id] => 3 ) [2] => stdClass Object ( [blog_id] => 5 ) ) ". Looks fine? */
/* loop to iterate through the ids and display info from each blog */
foreach( $site_blog_ids AS $site_blog_id ) {
print_r( "siteid= ".$site_blog_id."</br>" );
/* check output - this shows $site_blog_id is empty, no value. That's not right, should be each blog ID in turn from the site_blog_ids array. */
$oldblog = $wpdb->set_blog_id( $site_blog_id );
/* sets the system to use the loop blog ID instead of the current one. Since site_blog_id is empty, this doesn't work so the rest of the code uses the current blog, not the intended one. */
global $post;
$first_posts = get_posts('p=1'); //get the first post
foreach ( $first_posts AS $post ) {
setup_postdata();
the_title();
the_excerpt();
the_content();
the_category();
}
}
/* Tell the $wpdb object to go back to using the current site */
$wpdb->set_blog_id( $oldblog );
Upvotes: 0
Views: 141
Reputation: 737
Try the following:
/* loop to iterate through the ids and display info from each blog */
foreach( $site_blog_ids AS $site_blog_id ) {
print_r( "siteid= ". $site_blog_id->blog_id ."</br>");
/* check output - this shows $site_blog_id is empty, no value. That's not right, should be each blog ID in turn from the site_blog_ids array. */
Upvotes: 1
Reputation: 20889
print_r( "siteid= ".$site_blog_id."</br>" );
is incorrect.
By the time it hits the printr
section, it's looking at that as a string.
I think what you were attempting to do was:
echo "siteid=". print_r($site_blog_id, true) ."</br>";
Upvotes: 0