如何将WP多站点列表保存为CPT并配置ACF关联字段
WordPress多站点子站点关联ACF字段实现方案
方案一:将子站点同步为自定义文章类型(CPT)
1. 注册站点信息CPT
先在网络主站点(或指定管理站点)注册一个用于存储子站点信息的CPT,比如命名为site_entry:
function register_site_entry_cpt() { $args = [ 'label' => '站点条目', 'public' => true, 'show_ui' => true, 'supports' => ['title'], 'hierarchical' => false, 'menu_icon' => 'dashicons-admin-site' ]; register_post_type('site_entry', $args); } add_action('init', 'register_site_entry_cpt');
2. 编写同步脚本
通过get_sites()遍历所有子站点,获取基础信息和ACF站点选项,同步到CPT文章中。可以添加后台触发按钮或定时任务执行:
function sync_sites_to_cpt() { if (!current_user_can('manage_network')) return; $sites = get_sites(); foreach ($sites as $site) { // 切换到子站点获取数据 switch_to_blog($site->blog_id); $site_name = get_bloginfo('name'); $site_url = get_bloginfo('url'); // 获取子站点的ACF站点选项 $acf_options = get_fields('option') ?: []; restore_current_blog(); // 检查是否已存在对应CPT文章 $existing_post = get_posts([ 'post_type' => 'site_entry', 'meta_key' => 'site_blog_id', 'meta_value' => $site->blog_id, 'post_status' => 'publish', 'numberposts' => 1 ]); $post_args = [ 'post_title' => $site_name, 'post_status' => 'publish', 'post_type' => 'site_entry' ]; // 存在则更新,不存在则新建 if (!empty($existing_post)) { $post_args['ID'] = $existing_post[0]->ID; } $post_id = wp_insert_post($post_args); // 保存站点核心信息 update_post_meta($post_id, 'site_blog_id', $site->blog_id); update_post_meta($post_id, 'site_url', $site_url); // 保存ACF站点选项作为CPT自定义字段 foreach ($acf_options as $key => $value) { update_post_meta($post_id, "site_acf_{$key}", $value); } } } // 添加后台触发按钮(在CPT列表页显示) add_action('admin_notices', function() { if (get_current_screen()->post_type !== 'site_entry' || !current_user_can('manage_network')) return; echo '<div class="notice notice-info"><p><a href="' . admin_url('edit.php?post_type=site_entry&sync_sites=1') . '" class="button">同步所有子站点到CPT</a></p></div>'; }); add_action('admin_init', function() { if (isset($_GET['sync_sites']) && current_user_can('manage_network')) { sync_sites_to_cpt(); wp_redirect(admin_url('edit.php?post_type=site_entry')); exit; } });
3. 配置ACF关联字段
在子站点的ACF字段组中添加关联字段,设置关联的文章类型为site_entry,即可在后台选择同步后的站点条目。
4. 维护优化
- 定时同步:用
wp_schedule_event设置每日/每周同步,确保数据更新及时 - 增量同步:记录上次同步时间,仅同步更新过的站点(可通过
get_blog_details()获取站点修改时间) - 字段过滤:若无需同步所有ACF选项,可指定字段白名单,减少冗余数据
方案二:直接动态生成ACF站点选择列表(无需CPT)
如果不需要CPT的额外功能(如分类、标签),可以直接通过ACF钩子动态生成站点选择列表,更轻量:
function acf_load_site_choices($field) { $field['choices'] = []; $sites = get_sites(); foreach ($sites as $site) { switch_to_blog($site->blog_id); $site_label = sprintf('%s (%s)', get_bloginfo('name'), get_bloginfo('url')); restore_current_blog(); $field['choices'][$site->blog_id] = $site_label; } return $field; } // 替换为你的ACF字段键 add_filter('acf/load_field/key=field_your_site_select_key', 'acf_load_site_choices');
选择站点后,前端显示时可通过switch_to_blog($selected_site_id)获取对应站点的信息和ACF选项。
内容的提问来源于stack exchange,提问作者Temak
相关产品推荐
相关产品推荐

