Copy options: Automatically copy when options are updated

The following snippet will automatically copy options to blogs when they are modified.


/**
	@brief		Reacts to options being updated and then selectively broadcasts them to other blogs.
	@since		2020-02-27 18:00:17
**/
function bc_update_option( $option_name )
{
	// Config

	// Specify which options to watch and to which to copy them.
	// This array contains several subarrays (sets) of blogs and options.
	$options_to_copy =
	[
		[	// This is a set
			'blogs' => [ 1, 2, 3, 12 ],
			'options' => [
				'blogdescription',
				'option2',
			],
		],	// End of set
		// Another set...
		// Another set...
	];
	// End of config.

	global $bc_update_option_syncing;

	// To prevent recursion.
	if ( $bc_update_option_syncing === true )
		return;

	$bc_update_option_syncing = true;

	foreach( $options_to_copy as $set )
	{
		// In each set, there is an array containing options and blogs.
		if ( ! in_array( $option_name, $set[ 'options' ] ) )
			continue;
		// This set contains the option we are looking for.
		$co = broadcast_copy_options();
		// Create the action that will do the copying.
		$action = $co->new_action( 'do_copy' );
		$action->blogs = $set[ 'blogs' ];

		// Collect all of the options we are going to copy.
		$action->options_to_copy = [];
		foreach( $set[ 'options' ] as $key )
			$action->options_to_copy[ $key ] = get_option( $key );

		$co->debug( 'Option %s was updated! Copying %s to %s', $option_name, $action->options_to_copy, $action->blogs );
		$action->execute();
	}

	$bc_update_option_syncing = false;
}
add_action( 'update_option', 'bc_update_option' );