我如何才能信任Switch_to_Blog()?

时间:2014-03-18 作者:fuxia

当我打电话时switch_to_blog() 有了博客id,我不知道这个博客是否真的存在。函数始终返回TRUE.

测试用例:

switch_to_blog( PHP_INT_MAX );
$post = get_post( 1 );
restore_current_blog();
这将导致向用户公开的数据库错误。我怎样才能防止这种情况?

真实世界用例

我是Multilingual Press. 当用户翻译帖子时,会出现如下屏幕:

enter image description here

现在可能会发生以下情况:

她成功地保存了帖子,并继续翻译帖子switch_to_blog() 通常在多个不同的班级,所以速度必须快。

3 个回复
最合适的回答,由SO网友:fuxia 整理而成

@G.M.’s idea to cache the check has lead me to the following helper function. I’ve put it into the global namespace to have it available everywhere.

The function doesn’t say anything about the blog status, just if it exists and is not marked as deleted. The database query is very fast (0.0001 seconds) and runs just one query per site id, no matter how often the function is called.

if ( ! function_exists( \'blog_exists\' ) ) {

    /**
     * Checks if a blog exists and is not marked as deleted.
     *
     * @link   http://wordpress.stackexchange.com/q/138300/73
     * @param  int $blog_id
     * @param  int $site_id
     * @return bool
     */
    function blog_exists( $blog_id, $site_id = 0 ) {

        global $wpdb;
        static $cache = array ();

        $site_id = (int) $site_id;

        if ( 0 === $site_id )
            $site_id = get_current_site()->id;

        if ( empty ( $cache ) or empty ( $cache[ $site_id ] ) ) {

            if ( wp_is_large_network() ) // we do not test large sites.
                return TRUE;

            $query = "SELECT `blog_id` FROM $wpdb->blogs
                    WHERE site_id = $site_id AND deleted = 0";

            $result = $wpdb->get_col( $query );

            // Make sure the array is always filled with something.
            if ( empty ( $result ) )
                $cache[ $site_id ] = array ( \'do not check again\' );
            else
                $cache[ $site_id ] = $result;
        }

        return in_array( $blog_id, $cache[ $site_id ] );
    }
}

Usage

if ( ! blog_exists( $blog_id ) )
    return new WP_Error( \'410\', "The blog with the id $blog_id has vanished." );
SO网友:Santukon
if( get_blog_details( [ \'blog_id\' => $blogIdToTest ] ) ) {
 // Exists
} else {
 // Dont exists
}
SO网友:Alexander Behling

您可以使用带有博客id的get\\u站点来存档此内容。

从文档中(https://developer.wordpress.org/reference/functions/get_site/):返回站点对象(WP\\u Site | null),如果未找到,则返回null。

所以你要做的就是这样:

// Replace PHP_INT_MAX with the var which holds the site id you want to check against
if(!is_null(get_site(PHP_INT_MAX)){
//do stuff if site exists
}
else{
// do stuff if the site doesn\'t exists (anymore)
}

结束

相关推荐

How to set up wp multisite?

安装所有台阶后(http://codex.wordpress.org/Create_A_Network) 我尝试创建网站。我无法访问创建的任何网站的仪表板。它表示找不到页面(错误404)。为了启动fresh,我卸载了WP,然后按照每个步骤安装。我不知道该怎么办。我只能访问根站点的仪表板。其余的我都不行。