問題描述

當我呼叫 switch_to_blog()的部落格 ID,我不知道這個部落格是否真的存在。該函式始終為 TRUE

測試用例:

switch_to_blog( PHP_INT_MAX );
$post = get_post( 1 );
restore_current_blog();

這將導致暴露給使用者的資料庫錯誤。我該如何防範?

現實世界用例

我是 Multilingual Press 的首席開發人員。當使用者翻譯帖子時,她會收到如下螢幕:

現在可能發生以下情況:

  1. 她成功儲存了該帖子,並繼續翻譯該帖子。

  2. 另一位使用者,網路管理員,在寫作時會刪除德文部落格。

  3. 她再次點選儲存並獲取資料庫錯誤。

我想避免這種情況。如果目標部落格存在,我如何快速檢查?我經常在多個不同的類別中呼叫 switch_to_blog(),所以它必須很快。

最佳解決方案

@ G.M. 快取檢查的想法導致我進行以下幫助函式。我將它放入全域性名稱空間,讓它可以隨處可見。

該功能不會對部落格狀態做任何說明,只要它存在並且沒有標記為已刪除。資料庫查詢非常快 (0.0001 秒),並且每個站點 id 只執行一個查詢,無論呼叫該函式多長時間。

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 ] );
    }
}

用法

if ( ! blog_exists( $blog_id ) )
    return new WP_Error( '410', "The blog with the id $blog_id has vanished." );

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。