SRD75

add_hreflang_attribute

May 6th, 2022 (edited)
686
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.44 KB | None | 0 0
  1. /**
  2. * ADD HREFLANG ATTRIBUTES
  3. * Automatically append hreflang with network URL, language, and permalink to all pages
  4. */
  5.  
  6. function add_hreflang_attribute() {
  7.    $site_url = network_site_url(); // base URL
  8.    $alt_langs = array( '', 'au', 'uk' ); // two-letter language code
  9.    $page_path = substr(get_permalink(), strlen(home_url('/'))); // path of page after base URL
  10.    
  11.    if (!( is_singular( 'locations' ) ) ) {
  12.        
  13.        if ( is_post_type_archive('locations') ) {
  14.            
  15.            echo '<link rel="alternate" href="' . $site_url . $page_path . '" hreflang="x-default" />';
  16.            
  17.            // loop through the alternative languages, and get the appropriate hreflang tag for each that exists
  18.            foreach ($alt_langs as $lang) {
  19.                $updated_url_lang_path = $site_url . $lang . '/locations/';
  20.                $url_headers = @get_headers($updated_url_lang_path);
  21.                if($url_headers && strpos( $url_headers[0], '200')) {
  22.                    if ($lang == 'uk') {
  23.                        echo '<link rel="alternate" href="' . $updated_url_lang_path . '" hreflang="en-gb" />'. PHP_EOL;
  24.                    } else {
  25.                        echo '<link rel="alternate" href="' . $updated_url_lang_path . '" hreflang="en-' . $lang . '" />'. PHP_EOL;
  26.                    }
  27.                }
  28.            }
  29.            
  30.        } else {
  31.            
  32.            // loop through the alternative languages, and get the appropriate hreflang tag for each that exists
  33.            foreach ($alt_langs as $lang) {
  34.                $updated_url_lang_path = $site_url . $lang . '/' . $page_path;
  35.                $url_headers = @get_headers($updated_url_lang_path);
  36.                if($url_headers && strpos( $url_headers[0], '200')) {
  37.                    if ($lang == 'uk') {
  38.                        echo '<link rel="alternate" href="' . $updated_url_lang_path . '" hreflang="en-gb" />'. PHP_EOL;
  39.                    } elseif ($lang == '') {
  40.                      
  41.                    }
  42.                    else {
  43.                        echo '<link rel="alternate" href="' . $updated_url_lang_path . '" hreflang="en-' . $lang . '" />'. PHP_EOL;
  44.                    }
  45.                }
  46.            }
  47.            
  48.            // set primary as x-default
  49.            echo '<link rel="alternate" href="' . $site_url . $page_path . '" hreflang="x-default" />';
  50.            
  51.        }
  52.        
  53.    }
  54.  
  55. }
  56. add_action('wp_head', 'add_hreflang_attribute', 1);
Add Comment
Please, Sign In to add comment