0

I've been working on a Wordrepss multisite network and came across very common requirement of displaying a common navigation menu across all sites.

Use switch_to_blog() and restore_current_blog() before and after wp_nav_menu(...) respectively, right?

So did I. But, late I was in noticing that it re-ran (at-least but not limited to) posts_results and the_posts filters. So the posts_results filter would be called 3 times instead of 1 and would get following $posts parameter passed in.

1st time: The expected parameter. The post/posts to display on current page

2nd time: This call is probably result of switch_to_blog() call. This time the posts_results filter handler would be passed the menu items array.

3rd time: This call is probably result of restore_current_blog() call, and is the strangest. This time the posts_results filter handler would be passed, brace for it, the pages that are linked in the menu it just displayed in 2nd time.

removing the switch/restore calls removes this behavior and the filters are called only one time.

I figured it out the hard way after noticing that the callbacks to aforementioned hooks kept executing multiple times and were getting unexpected post_type to them. I first took it as default behavior of multisite and tried to work around it by checking post_type and executing code only when it got the expected post_type. But after looking into it closely, I think it is an unexpected behavior since it is not documented anywhere and doesn't make much sense either.

My question,
Is this behavior unexpected?
If not then what is the use-case for this behavior? If yes then how to avoid it?

I'm using latest version of Wordpress, version 4.3.

Any help regarding this matter will be greatly appreciated.

Thanks.

0

The typical answer to anything switch_to_blog() is — no it shouldn't, yes it is a mess. Simply put WP architecture doesn't posses the capability of making such clean switch from one blog to another in the runtime. It's a bit of wishful thinking — some things work, some very much break.

In your specific case it is a little puzzling why would query–related hooks fire, since the switch itself shouldn’t involve querying posts. The most reliable would be to dump how they are called up, for example using wp_debug_backtrace_summary().

  • Thanks for the answer, I'll update the question with debug backtrace shortly. – Ejaz Sep 9 '15 at 21:45

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.