switch_to_blog()
时,我不知道该博客是否确实存在。该函数始终返回TRUE
。测试用例:
switch_to_blog( PHP_INT_MAX );
$post = get_post( 1 );
restore_current_blog();
这将导致数据库错误,并向用户公开。如何防止这种情况?
现实世界中的用例
我是Multilingual Press的首席开发人员。用户翻译帖子时,会得到如下屏幕:
现在可以发生以下情况:
她成功保存该帖子,并继续翻译该帖子。
另一个用户,网络管理员,在写作时删除了德语博客。
她再次单击保存并获得数据库错误。
我想避免这种情况。如何快速检查目标博客是否存在?我经常在多个不同的类中调用
switch_to_blog()
,因此必须快速。#1 楼
@GM缓存支票的想法使我进入了以下帮助程序功能。我已将其放入全局命名空间中,以使其在任何地方都可以使用。该功能不会说明博客状态,即使它存在且未标记为已删除。数据库查询非常快(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." );
评论
为什么$ wpdb-> get_results + wp_list_pluck而不是仅(int)$ wpdb-> get_var?但是+1,我认为核心switch_to_blog中应该有类似的内容...
– gmazzap♦
2014年3月18日14:07
@GM get_var()仅返回一个结果。我已经使用了get_col(),并且确保没有再次获取空结果。
– fuxia♦
2014年3月18日在20:21
嗯,好吧。。。我现在最好阅读查询,您将获得特定站点ID的所有博客ID,首先阅读时,您一次只能获得一个博客ID(传递给函数的那个博客ID)...确定数组方式更好。很抱歉,无法再次+1 :)
– gmazzap♦
2014年3月18日在20:37
#2 楼
您可以使用带有博客ID的get_site来对此进行归档。从文档(https://developer.wordpress.org/reference/functions/get_site/):
返回( WP_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)
}
评论
$ wpdb-> blogid怎么样?和钩子wp_insert_post_data?@JMau get_post()只是读取。在上一次保存和下一次编辑屏幕重新加载之间可能会停留很长时间。
每个请求在wp_blogs表中的blog_id(其中已删除= 0)的SQL缓存查询吗?
@GM从{$ wpdb-> blogs}中选择blog_id,其中site_id =%d AND public ='1'AND archived ='0'AND spam ='0'AND Deleted ='0'
@toscho大声思考...有wp_cache_switch_to_blog(),但它仅对持久性缓存有所帮助,而不是页面WP上的默认值。无论如何,对我来说,您在哪里想检查博客是否存在还不清楚,是什么时候删除某博客或某人尝试撰写指向另一博客的翻译后帖子(以另一种语言提供相同内容)? >