Question

OK, so WordPress has been destroying me this afternoon and this particular issue I really can't figure out. We are building a multisite network and for our particular purpose need to loop through each multisite to get some post data, etc.

Test Case #1:

$sites = array ();

foreach(wp_get_sites() as $blog_details) {

    // switch to the blog
    switch_to_blog($blog_details['blog_id']);

    // store the blog id & name
    $sites[$blog_details['blog_id']] = get_bloginfo('name');

    // restore the current blog
    // when coming out of the loop
    restore_current_blog();
}

We are looping through each site, switching to that blog based on ID and storing the ID and name as a key => value pair to use later on. At the end of each iteration, we are restoring the last blog. The resulting array is like so -

Array
(
    [1] => Site 1
    [2] => Site 2
    [3] => Site 3
    [4] => Site 4
    [5] => Site 5
    [6] => Site 6
)

I have looked and can confirm that the ID's and names are correct - great!

Test Case #2:

foreach($sites as $blog_id => $name) {

    switch_to_blog($blog_id);

    $sites[$blog_id] = get_bloginfo('name');

    restore_current_blog();
}

We are looping through our generated array of blog ID => name values (as shown above), switching to the appropriate blog ID (which I have debugged and can verify the IDs are correct) and then setting the retrieved blog name against the existing array. Our new resulting array looks like this -

Array
(
    [1] => Site 1
    [2] => Site 1
    [3] => Site 1
    [4] => Site 1
    [5] => Site 1
    [6] => Site 1
)

They are now all displaying as site 1?! You can see the keys are still correct and as expected. I have tried typecasting the keys to various different types (string, int etc) when using the switch_to_blog($blog_id) method but to no avail.

The real issue here (not just the test case) is not that I can't get the blog name so please no suggestions on a different call to get a multisite blog name but that I can't query any of the multisites other than site 1.

I really hope someone can help me out on this!

Was it helpful?

Solution

You might be running up against WordPress's global $blog_id variable in test case #2.

Try this:

foreach($sites as $my_blog_id => $name) {

    switch_to_blog($my_blog_id);

    $sites[$my_blog_id] = get_bloginfo('name');

    restore_current_blog();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top