Add access to a blog

How to programmatically add Broadcast access to a blog.

The user does not have to be a member of the target blog to be able to broadcast to it.

Based on user ID

This snippet adds access based on the ID of the user.

function my_threewp_broadcast_get_user_writable_blogs( $action )
{
	$users_and_blogs = [
		// User ID			// Blog IDs
		4				=> [ 4, 5, 10 ],
		6				=> [ 88, 89, 91 ],
	];
	if ( ! isset( $users_and_blogs[ $action->user_id ] ) )
		return;
	
	foreach( $users_and_blogs[ $action->user_id ] as $blog_id )
		$action->add_access( $blog_id );
}
// Broadcast fills the blog list at prio 100, so use a higher number.
add_action( 'threewp_broadcast_get_user_writable_blogs', 'my_threewp_broadcast_get_user_writable_blogs', 200 );

Based on user role

This snippet will add access depending on which role(s) the user has.

function my_threewp_broadcast_get_user_writable_blogs( $action )
{
	$roles_and_blogs = [
		// Role				// Blog IDs
		'contributor'		=> [ 88, 89, 91 ],
		'editor'			=> [ 4, 5, 10 ],
	];

	$user = wp_get_current_user();

	foreach( $user->roles as $role_name )
	{
		if ( ! isset( $roles_and_blogs[ $role_name ] ) )
			continue;
		foreach( $roles_and_blogs[ $role_name ] as $blog_id )
			$action->add_access( $blog_id );
	}
}
// Broadcast fills the blog list at prio 100, so use a higher number.
add_action( 'threewp_broadcast_get_user_writable_blogs', 'my_threewp_broadcast_get_user_writable_blogs', 200 );