PHP Snippet 1:
function mm_add_hreflang_attribute() {
if (!( is_singular( 'locations' ) ) ) {
$sites = array(
array('', 'x-default'),
array('en-gb/', 'en-gb'),
array('en-au/', 'en-au'),
);
if ( is_post_type_archive('locations') ) {
foreach ( $sites as $site ) {
$site_url = network_site_url();
$page_path = 'locations/';
$geo_url = $site[0];
$hreflang = $site[1];
$url = $site_url . $geo_url . $page_path;
echo '<link rel="alternate" href="' . $url . '" hreflang="' . $hreflang . '" />'. PHP_EOL;
}
} else {
foreach ( $sites as $site ) {
$site_url = network_site_url();
$page_path = substr(get_permalink(), strlen(home_url('/')));
$geo_url = $site[0];
$hreflang = $site[1];
$url = $site_url . $geo_url . $page_path;
echo '<link rel="alternate" href="' . $url . '" hreflang="' . $hreflang . '" />'. PHP_EOL;
}
}
}
}
add_action('wp_head', 'mm_add_hreflang_attribute', 1);
PHP Snippet 2:
function mm_add_hreflang_attribute() {
if (!( is_singular( 'locations' ) ) ) {
$sites = array(
array('', 'x-default'),
array('en-gb/', 'en-gb'),
array('en-au/', 'en-au'),
);
if ( is_post_type_archive('locations') ) {
foreach ( $sites as $site ) {
$site_url = network_site_url();
$page_path = 'locations/';
$geo_url = $site[0];
$hreflang = $site[1];
$url = $site_url . $geo_url . $page_path;
echo '<link rel="alternate" href="' . $url . '" hreflang="' . $hreflang . '" />'. PHP_EOL;
}
}
else
{
foreach ( $sites as $site ) {
$site_url = network_site_url();
$page_path = substr(get_permalink(), strlen(home_url('/')));
$geo_url = $site[0];
$hreflang = $site[1];
$url = $site_url . $geo_url . $page_path;
echo '<link rel="alternate" href="' . $url . '" hreflang="' . $hreflang . '" />'. PHP_EOL;
}
}
}
}
add_action('wp_head', 'mm_add_hreflang_attribute', 1);