I have a multisite network and have ACF site options on each subsite. The subsites are related eg some might be in the same area. I would like to add an ACF relationship field to each subsite where a list of all subsites can be displayed and sites can be picked from that.
To do this, the list of subsites needs to be a custom post type. I have looked but cant seem to find anyway to save list of all sites under a multisite network as posts under a custom post type. I am able to use get_sites() and switch_to_blog() to get basic info about the subsites but saving them as a cpt is the blocker. It would also be nice to have some of the site options saved as custom fields under that post type.
Anyone done something similar or any idea how to achieve this please?
I was able to do this eventually with the switch_to_blog function to get the ACF field values and then switching back to the main blog where I need the info and inserting the data as new posts in my cpt.
function get_subsite_data() {
$subsites = get_sites();
$currentSiteId = get_current_blog_id();
$mainSiteId = get_main_site_id();
$mainSiteURL = get_site_url();
if ($currentSiteId == $mainSiteId) {
foreach ($subsites as $subsite) {
$siteId = $subsite->blog_id;
$siteName = get_blog_details($siteId)->blogname;
if ($siteId == $mainSiteId) {
continue;
}
switch_to_blog($siteId);
// retrieve site options
$subsiteAcfData = get_blog_option($siteId, 'acf_option');
restore_current_blog();
// another function to check if subsite has been imported already
$subsitePostID = get_post_id_by_subsite_id($siteId);
if (!$subsitePostID) {
$args = [
'post_title' => $siteName,
'post_status' => 'publish',
'post_author' => get_current_user_id(),
'post_content' => '',
'post_type' => 'custom_post_type',
];
$subsitePostID = wp_insert_post($args);
} else {
$args = array(
'ID' => $subsitePostID,
'post_title' => $siteName
);
wp_update_post($args);
}
// save site info to main site cpt acf fields
$postMetaData = [
'subsite_id' => $siteId,
'acf_field' => $subsiteAcfData,
'_subsite_id' => 'field_12345abc',
'_acf_field' => 'field_12345abc'
];
foreach ($postMetaData as $key => $value) {
update_post_meta($subsitePostID, $key, $value);
}
}
}
}