Created
June 20, 2024 15:43
-
-
Save tomfinitely/d074e6aebf733f5e03b90a7530f9da04 to your computer and use it in GitHub Desktop.
Synchronize Reusable Blocks Between WordPress Multisite Subsites
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Sync the reusable blocks between the sites of the multisite. | |
* | |
* @param int $post_id The post id. | |
* @param WP_Post $post The post object. | |
*/ | |
add_action( 'publish_wp_block', 'slug_sync_reusable_blocks', 10, 2 ); | |
function slug_sync_reusable_blocks( $post_id, $post ) { | |
// Check if the post already has a sync_hash or create one. | |
if ( get_post_meta( $post_id, 'sync_hash', true ) !== '' ) { | |
$sync_hash = get_post_meta( $post_id, 'sync_hash', true ); | |
} else { | |
$sync_hash = uniqid( $post->post_title ); | |
update_post_meta( $post_id, 'sync_hash', $sync_hash ); | |
} | |
$current_site_id = get_current_blog_id(); | |
// Get the site IDs. | |
$sites = get_sites( | |
[ | |
'fields' => 'ids', | |
] | |
); | |
remove_action( 'publish_wp_block', 'slug_sync_reusable_blocks', 10 ); | |
foreach ( $sites as $site_id ) { | |
if ( $current_site_id !== $site_id ) { | |
switch_to_blog( $site_id ); | |
// Check if we already synced the block and only need to update it. | |
$existing_block_query = new WP_Query( | |
[ | |
'post_type' => 'wp_block', | |
'no_found_rows' => true, | |
'update_post_meta_cache' => false, | |
'update_post_term_cache' => false, | |
'fields' => 'ids', | |
'meta_key' => 'sync_hash', | |
'meta_value' => $sync_hash, | |
'posts_per_page' => 1, | |
] | |
); | |
if ( $existing_block_query->have_posts() ) { | |
// Update the post. | |
$existing_post_id = $existing_block_query->posts[0]; | |
wp_update_post( | |
[ | |
'ID' => $existing_block_query->posts[0], | |
'post_content' => $post->post_content, | |
'post_title' => $post->post_title, | |
'post_status' => 'publish', | |
] | |
); | |
} else { | |
// Create the post if we do not have the block already. | |
wp_insert_post( | |
[ | |
'post_type' => 'wp_block', | |
'post_content' => $post->post_content, | |
'post_title' => $post->post_title, | |
'post_status' => 'publish', | |
'meta_input' => | |
[ | |
'sync_hash' => $sync_hash, | |
], | |
] | |
); | |
} | |
restore_current_blog(); | |
} | |
} | |
add_action( 'publish_wp_block', 'slug_sync_reusable_blocks', 10, 2 ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
From https://krautpress.de/2020/wiederverwendbare-bloecke-zwischen-sites-einer-multisite-synchronisieren/