WPML: Broadcasting from non-WPML to WPML blogs

This snippet allows broadcasting from non-WPML enabled blogs to blogs in the network with WPML.

Normally, doing this will result in hidden posts since they do not have a language assigned. The snippet will assign the blog’s default language to the newly-broadcasted post.

/**
	@brief		Force a default language for this post broadcasted from a non-WPML blog.
	@since		2020-01-29 17:00:43
**/
function bc_threewp_broadcast_broadcasting_before_restore_current_blog( $action )
{
	// This should only apply to new posts.
	$bcd = $action->broadcasting_data;
	if ( ! $bcd->new_child_created )
		return;

	// Is WPML is active on this blog?
	$plugin_name = 'sitepress-multilingual-cms/sitepress.php';
	$active = get_option( 'active_plugins' );
	$active = in_array( $plugin_name, $active );
	if ( ! $active )
		return;

	// Fetch the default language.
	$option = get_option( 'icl_sitepress_settings', true );
	$option = maybe_unserialize( $option );
	$default_language = $option[ 'default_language' ];

	// Fetch a new trid.
	global $wpdb;
	$table = $wpdb->prefix . 'icl_translations';
	$query = sprintf( "SELECT MAX( `trid` ) FROM `%s`", $table );
	ThreeWP_Broadcast()->debug( 'Active WPML: %s', $query );
	$trid = $wpdb->get_var( $query );
	$trid++;
	ThreeWP_Broadcast()->debug( 'Active WPML: New trid is %s', $trid );

	// Insert the new translation row.
	$query = sprintf( "INSERT INTO `%s` ( `element_type`, `element_id`, `trid`, `language_code` ) VALUES ( 'post_%s', '%s', '%s', '%s' )",
		$table,
		$bcd->post->post_type,
		$bcd->new_post( 'ID' ),
		$trid,
		$default_language
	);
	ThreeWP_Broadcast()->debug( 'Active WPML: %s', $query );
	$wpdb->query( $query );
}
add_action( 'threewp_broadcast_broadcasting_before_restore_current_blog', 'bc_threewp_broadcast_broadcasting_before_restore_current_blog' );