multisite - restore_current_blog required after switch_to_blog, if I use that in a function?

admin2025-06-04  1

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?

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?

Share Improve this question asked Jan 23, 2019 at 16:23 Galgóczi LeventeGalgóczi Levente 1893 silver badges17 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

switch_to_blog changes values of global variables (as you can see here: https://core.trac.wordpress/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)

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748982164a315364.html

最新回复(0)