| 642 | |
| 643 | /** |
| 644 | * Adds hreflang link attributes to WordPress.org pages. |
| 645 | * |
| 646 | * @link https://support.google.com/webmasters/answer/189077?hl=en Use hreflang for language and regional URLs. |
| 647 | * @link https://sites.google.com/site/webmasterhelpforum/en/faq-internationalisation FAQ: Internationalisation. |
| 648 | */ |
| 649 | public function hreflang_link_attributes() { |
| 650 | wp_cache_add_global_groups( array( 'locale-associations' ) ); |
| 651 | |
| 652 | if ( false === ( $sites = wp_cache_get( 'local-sites', 'locale-associations' ) ) ) { |
| 653 | |
| 654 | $sites = Plugin_I18n::instance()->find_all_translations_for_plugin( get_pots()->post_name, 'stable-readme', '90' ); |
| 655 | |
| 656 | require_once GLOTPRESS_LOCALES_PATH; |
| 657 | |
| 658 | foreach ( $sites as $site ) { |
| 659 | $gp_locale = \GP_Locales::by_field( 'wp_locale', $site ); |
| 660 | if ( ! $gp_locale ) { |
| 661 | unset( $sites[ $site ] ); |
| 662 | continue; |
| 663 | } |
| 664 | |
| 665 | // Note that Google only supports ISO 639-1 codes. |
| 666 | if ( isset( $gp_locale->lang_code_iso_639_1 ) && isset( $gp_locale->country_code ) ) { |
| 667 | $hreflang = $gp_locale->lang_code_iso_639_1 . '-' . $gp_locale->country_code; |
| 668 | } elseif ( isset( $gp_locale->lang_code_iso_639_1 ) ) { |
| 669 | $hreflang = $gp_locale->lang_code_iso_639_1; |
| 670 | } elseif ( isset( $gp_locale->lang_code_iso_639_2 ) ) { |
| 671 | $hreflang = $gp_locale->lang_code_iso_639_2; |
| 672 | } elseif ( isset( $gp_locale->lang_code_iso_639_3 ) ) { |
| 673 | $hreflang = $gp_locale->lang_code_iso_639_3; |
| 674 | } |
| 675 | |
| 676 | if ( $hreflang ) { |
| 677 | $sites[ $site->locale ]->hreflang = strtolower( $hreflang ); |
| 678 | } else { |
| 679 | unset( $sites[ $site->locale ] ); |
| 680 | } |
| 681 | } |
| 682 | |
| 683 | // Add en_US to the list of sites. |
| 684 | $sites['en_US'] = (object) array( |
| 685 | 'locale' => 'en_US', |
| 686 | 'hreflang' => 'en', |
| 687 | 'subdomain' => '' |
| 688 | ); |
| 689 | |
| 690 | uasort( $sites, function( $a, $b ) { |
| 691 | return strcasecmp( $a->hreflang, $b->hreflang ); |
| 692 | } ); |
| 693 | |
| 694 | wp_cache_set( 'local-sites', $sites, 'locale-associations' ); |
| 695 | } |
| 696 | |
| 697 | foreach ( $sites as $site ) { |
| 698 | $url = sprintf( |
| 699 | 'https://%swordpress.org%s', |
| 700 | $site->subdomain ? "{$site->subdomain}." : '', |
| 701 | $_SERVER[ 'REQUEST_URI' ] |
| 702 | ); |
| 703 | |
| 704 | printf( |
| 705 | '<link rel="alternate" href="%s" hreflang="%s" />' . "\n", |
| 706 | esc_url( $url ), |
| 707 | esc_attr( $site->hreflang ) |
| 708 | ); |
| 709 | } |
| 710 | } |