$conf, $runtime; function_exists('chdir') AND chdir(APP_PATH); $r = 'mysql' == $conf['cache']['type'] ? website_set('runtime', $runtime) : cache_set('runtime', $runtime); } function runtime_truncate() { global $conf; 'mysql' == $conf['cache']['type'] ? website_set('runtime', '') : cache_delete('runtime'); } register_shutdown_function('runtime_save'); ?>multisite - restore_current_blog required after switch_to_blog, if I use that in a function?|Programmer puzzle solving
最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

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

matteradmin11PV0评论
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)

Post a comment

comment list (0)

  1. No comments so far