0

In my root blog (1), i have a custom post type that can be linked to an existing blog of my network. It does so by recording in post metas the ID of the blog it is linked to. I use _blog_id as a name for this data.

In a page of this root blog, i list these custom posts, and i easily retreive the meta i saved:

<?php while ( have_posts() ) : the_post();
$blog_id = get_post_meta(get_the_id(), '_blog_id', true);

Now, i have the ID of the blog i want information from, so i try the following:

switch_to_blog($blog_id);
$blog_url = get_bloginfo('url');
restore_current_blog();

Unfortunately, that doesn't work because $blog_url has the URL of the root blog.

Worse: switch_to_blog() works but not restore_current_blog(), because subsequent calls to the LOOP functions now work in the sub-blog. For example, when calling the_post_thumbnails(), the image source is referred by "/uploads/sites/2/2014..." while i'm in the root site.

As you could guess, i have two questions:

  1. How to retreive blog info of another blog in the network, from the template of a blog?
  2. Why does switch_to_blog(), followed by restore_current_blog() makes the LOOP functions to behave incorrectly?

Thank you everyone! Have a great weekend!

1
  • Disable all plugins. Are you still seeing the issue with switch_to_blog() / restore_current_blog()? If not, re-enable your plugins one by one till the issue re-emerges. That'll tell you which plugin, if any, is at fault. If it's not a plugin, try using a default WP theme -- Twenty Thirteen or Twenty Fourteen.
    – Pat J
    Feb 14 '14 at 23:06
0

@Pat J: thank you for your answer. As an old developer as i am, that was one of the first reflex i had, i disabled plugins, and even custom functions. Nothing ever helped. I forgot to mention that out.

But i found the solution, and that's quite stupid, read that:

$blog_id is somehow used in the loop (or generally in the template) so you should never assign this variable. $blog_id is a reserved variable in template! Now i'll remember ;)

What happened is that, by changing $blog_id's value, subsequent helper function calls were working on the wrong blog, thus using wrong upload folder for example.

It also addresses my first issue: network_site_url($sub_blog_id) gives me the URL of a foreign blog, as i needed. The $blog_id bug was affecting this behavior too.

Hope this helps!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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