
7折
减价出售
¥799
switch_to_blog
是 WordPress主题中最重要的函数之一,它允许开发者在运行时切换当前操作的站点上下文。本文将全面解析这个函数的用法、原理和最佳实践。
switch_to_blog( int $blog_id ): bool
// 保存当前站点ID
$original_blog_id = get_current_blog_id();
// 切换到目标站点
switch_to_blog($target_blog_id);
// 在目标站点执行操作
$posts = get_posts(['posts_per_page' => 5]);
// 恢复原始站点
restore_current_blog();
// 验证是否恢复成功
if (get_current_blog_id() !== $original_blog_id) {
throw new Exception('站点切换恢复失败');
}
当调用 switch_to_blog
时,WordPress 会:
$wpdb
, $wp_query
等)压入堆栈切换站点会影响以下全局变量:
$wpdb
– 数据库连接对象$posts
– 当前查询结果$post
– 当前文章对象$wp_rewrite
– 重写规则对象$wp_query
– 主查询对象function update_all_sites_option($option_name, $value) {
$sites = get_sites(['number' => 100]); // 限制100个站点防止超时
foreach ($sites as $site) {
switch_to_blog($site->blog_id);
update_option($option_name, $value);
restore_current_blog();
}
}
// 使用示例
update_all_sites_option('maintenance_mode', 'on');
function get_network_content($main_blog_id, $secondary_blog_id) {
switch_to_blog($main_blog_id);
$main_content = get_posts(['posts_per_page' => 3]);
switch_to_blog($secondary_blog_id); // 嵌套切换
$secondary_content = get_posts(['posts_per_page' => 3]);
restore_current_blog(); // 恢复到主站点
restore_current_blog(); // 恢复到原始站点
return [
'main' => $main_content,
'secondary' => $secondary_content
];
}
// 不推荐:频繁切换
foreach ($post_ids as $id) {
switch_to_blog($blog_id);
$post = get_post($id);
restore_current_blog();
// 处理$post...
}
// 推荐:批量处理
switch_to_blog($blog_id);
$posts = get_posts(['post__in' => $post_ids]);
restore_current_blog();
// 处理$posts...
function get_cross_blog_post($blog_id, $post_id) {
$cache_key = "cross_post_{$blog_id}_{$post_id}";
$post = wp_cache_get($cache_key, 'cross_posts');
if (false === $post) {
switch_to_blog($blog_id);
$post = get_post($post_id);
restore_current_blog();
wp_cache_set($cache_key, $post, 'cross_posts', HOUR_IN_SECONDS);
}
return $post;
}
// 处理插件不兼容情况
function safe_switch_to_blog($blog_id) {
global $some_plugin_global;
$original_blog = get_current_blog_id();
$original_plugin_data = $some_plugin_global;
switch_to_blog($blog_id);
// 重新初始化插件数据
if (class_exists('Some_Plugin')) {
$some_plugin_global = new Some_Plugin();
}
return function() use ($original_blog, $original_plugin_data) {
switch_to_blog($original_blog);
$some_plugin_global = $original_plugin_data;
};
}
// 使用示例
$restore = safe_switch_to_blog(2);
// 执行操作...
$restore(); // 恢复原始状态
// 确保总是成对使用
function with_blog($blog_id, $callback) {
switch_to_blog($blog_id);
try {
return $callback();
} finally {
restore_current_blog();
}
}
// 使用示例
$latest_posts = with_blog(3, function() {
return get_posts(['posts_per_page' => 5]);
});
switch_to_blog
是 WordPress多站点开发中的利器,但需要谨慎使用。理解其工作原理并遵循最佳实践,可以避免许多潜在问题,同时充分发挥多站点环境的优势。
减价出售
减价出售
减价出售
减价出售
电话咨询
1855-626-3292
微信咨询