Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * ADD HREFLANG ATTRIBUTES
- * Automatically append hreflang with network URL, language, and permalink to all pages
- */
- function add_hreflang_attribute() {
- $site_url = network_site_url(); // base URL
- $alt_langs = array( '', 'au', 'uk' ); // two-letter language code
- $page_path = substr(get_permalink(), strlen(home_url('/'))); // path of page after base URL
- if (!( is_singular( 'locations' ) ) ) {
- if ( is_post_type_archive('locations') ) {
- echo '<link rel="alternate" href="' . $site_url . $page_path . '" hreflang="x-default" />';
- // loop through the alternative languages, and get the appropriate hreflang tag for each that exists
- foreach ($alt_langs as $lang) {
- $updated_url_lang_path = $site_url . $lang . '/locations/';
- $url_headers = @get_headers($updated_url_lang_path);
- if($url_headers && strpos( $url_headers[0], '200')) {
- if ($lang == 'uk') {
- echo '<link rel="alternate" href="' . $updated_url_lang_path . '" hreflang="en-gb" />'. PHP_EOL;
- } else {
- echo '<link rel="alternate" href="' . $updated_url_lang_path . '" hreflang="en-' . $lang . '" />'. PHP_EOL;
- }
- }
- }
- } else {
- // loop through the alternative languages, and get the appropriate hreflang tag for each that exists
- foreach ($alt_langs as $lang) {
- $updated_url_lang_path = $site_url . $lang . '/' . $page_path;
- $url_headers = @get_headers($updated_url_lang_path);
- if($url_headers && strpos( $url_headers[0], '200')) {
- if ($lang == 'uk') {
- echo '<link rel="alternate" href="' . $updated_url_lang_path . '" hreflang="en-gb" />'. PHP_EOL;
- } elseif ($lang == '') {
- }
- else {
- echo '<link rel="alternate" href="' . $updated_url_lang_path . '" hreflang="en-' . $lang . '" />'. PHP_EOL;
- }
- }
- }
- // set primary as x-default
- echo '<link rel="alternate" href="' . $site_url . $page_path . '" hreflang="x-default" />';
- }
- }
- }
- add_action('wp_head', 'add_hreflang_attribute', 1);
Add Comment
Please, Sign In to add comment