245 | | * Adds hreflang link attributes to plugin pages. |
246 | | * |
247 | | * @link https://support.google.com/webmasters/answer/189077?hl=en Use hreflang for language and regional URLs. |
248 | | * @link https://sites.google.com/site/webmasterhelpforum/en/faq-internationalisation FAQ: Internationalisation. |
249 | | */ |
250 | | function hreflang_link_attributes() { |
251 | | if ( is_404() ) { |
252 | | return; |
253 | | } |
254 | | |
255 | | wp_cache_add_global_groups( array( 'locale-associations' ) ); |
256 | | |
257 | | if ( false === ( $sites = wp_cache_get( 'local-sites', 'locale-associations' ) ) ) { |
258 | | global $wpdb; |
259 | | |
260 | | $sites = $wpdb->get_results( 'SELECT locale, subdomain FROM locales', OBJECT_K ); |
261 | | if ( ! $sites ) { |
262 | | return; |
263 | | } |
264 | | |
265 | | require_once GLOTPRESS_LOCALES_PATH; |
266 | | |
267 | | foreach ( $sites as $site ) { |
268 | | $gp_locale = \GP_Locales::by_field( 'wp_locale', $site->locale ); |
269 | | if ( ! $gp_locale ) { |
270 | | unset( $sites[ $site->locale ] ); |
271 | | continue; |
272 | | } |
273 | | |
274 | | $hreflang = false; |
275 | | |
276 | | // Note that Google only supports ISO 639-1 codes. |
277 | | if ( isset( $gp_locale->lang_code_iso_639_1 ) && isset( $gp_locale->country_code ) ) { |
278 | | $hreflang = $gp_locale->lang_code_iso_639_1 . '-' . $gp_locale->country_code; |
279 | | } elseif ( isset( $gp_locale->lang_code_iso_639_1 ) ) { |
280 | | $hreflang = $gp_locale->lang_code_iso_639_1; |
281 | | } elseif ( isset( $gp_locale->lang_code_iso_639_2 ) ) { |
282 | | $hreflang = $gp_locale->lang_code_iso_639_2; |
283 | | } elseif ( isset( $gp_locale->lang_code_iso_639_3 ) ) { |
284 | | $hreflang = $gp_locale->lang_code_iso_639_3; |
285 | | } |
286 | | |
287 | | if ( $hreflang && 'art' !== $hreflang ) { |
288 | | $sites[ $site->locale ]->hreflang = strtolower( $hreflang ); |
289 | | } else { |
290 | | unset( $sites[ $site->locale ] ); |
291 | | } |
292 | | } |
293 | | |
294 | | // Add en_US to the list of sites. |
295 | | $sites['en_US'] = (object) array( |
296 | | 'locale' => 'en_US', |
297 | | 'hreflang' => 'en', |
298 | | 'subdomain' => '' |
299 | | ); |
300 | | |
301 | | uasort( $sites, function( $a, $b ) { |
302 | | return strcasecmp( $a->hreflang, $b->hreflang ); |
303 | | } ); |
304 | | |
305 | | wp_cache_set( 'local-sites', $sites, 'locale-associations' ); |
306 | | } |
307 | | |
308 | | foreach ( $sites as $site ) { |
309 | | $url = sprintf( |
310 | | 'https://%swordpress.org%s', |
311 | | $site->subdomain ? "{$site->subdomain}." : '', |
312 | | $_SERVER[ 'REQUEST_URI' ] |
313 | | ); |
314 | | |
315 | | printf( |
316 | | '<link rel="alternate" href="%s" hreflang="%s" />' . "\n", |
317 | | esc_url( $url ), |
318 | | esc_attr( $site->hreflang ) |
319 | | ); |
320 | | } |
321 | | } |
322 | | add_action( 'wp_head', __NAMESPACE__ . '\hreflang_link_attributes' ); |
323 | | |
324 | | /** |