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()
andrestore_current_blog()
before and afterwp_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.