Adding hreflang tags automatically in WordPress subdirectory multisite

Alternatively we can set the hreflang as a site meta for each site:

update_site_meta( 1, 'hreflang', 'x-default' );
update_site_meta( 3, 'hreflang', 'en-au' );
update_site_meta( 5, 'hreflang', 'en-gb' );

and then for the hreflang attribute use;

get_site_meta( $site->blog_id, 'hreflang' )

and for the href attribute:

get_home_url( $site->blog_id, $page_path )

If we want to skip the site meta and use:

$hreflangs = array(
    1 => 'x-default',
    3 => 'en-au',
    5 => 'en-gb',
);  

then the sites loop becomes:

$page_path = substr( get_permalink(), strlen( home_url("https://wordpress.stackexchange.com/") )); 

$sites = get_sites();
foreach ( $sites as $site ) {
    if ( isset( $hreflangs[ $site->blog_id ] ) ) {
        printf ( 
            '<link rel="alternate" href="%s" hreflang="%s" />'. PHP_EOL,
            esc_url( get_home_url( $site->blog_id, $page_path ) ),
            esc_attr( $hreflangs[ $site->blog_id ] )
        );
    }
}

One might further check if the page-path/slug exists on each site with e.g. get_page_by_path() or get_posts() via switch_to_blog().