restore_current_blog required after switch_to_blog, if I use that in a function?
-
14-04-2021 - |
Question
class Basics {
public function build_frontend_post_form( $blog_object ) {
switch_to_blog( $blog_object->blog_id );
if( !( current_user_can( 'administrator' ) and current_user_can( 'publish_posts' ) ) ) { restore_current_blog(); return false; }
restore_current_blog();
#DO STUFF
}
}
In the exclusion (and anyway if not necessary for my logic) I need to use it restore_current_blog, or enough the return false? So In this case the base blog will be restoring after the function or not?
Solution
switch_to_blog
changes values of global variables (as you can see here: https://core.trac.wordpress.org/browser/tags/5.0.3/src/wp-includes/ms-blogs.php#L801). It doesn’t matter if you call it in function or not - these variables will get changed.
So yes - you always have to call restore_current_blog
when you’ve done all you wanted with the switched blog.
Otherwise these variables will stay changed (so wpdb
will query wrong tables and so on)
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange