router = $router; } public function register(): void { if ( ! $this->router->is_frontend() ) { return; } add_action( 'wp_head', array( $this, 'hreflang' ), 2 ); add_filter( 'translateplus_bypass_query_filter', array( $this, 'is_sitemap' ) ); $locale = function () { return Languages::locale( Languages::current() ); }; add_filter( 'wpseo_locale', $locale ); add_filter( 'rank_math/opengraph/facebook/og_locale', $locale ); add_filter( 'seopress_social_og_locale', $locale ); } /** * Sitemap requests list content in every language. * * @param bool $bypass Bypass. */ public function is_sitemap( $bypass ): bool { if ( $bypass ) { return true; } global $wp; if ( $wp && ( ! empty( $wp->query_vars['sitemap'] ) || ! empty( $wp->query_vars['sitemap-subtype'] ) || ! empty( $wp->query_vars['seopress_sitemap'] ) || ! empty( $wp->query_vars['seopress_cpt'] ) ) ) { return true; } $uri = \TranslatePlus\Core\Request::uri(); return (bool) preg_match( '#(sitemap[^/]*\.xml|wp-sitemap)#i', $uri ); } /** * Alternate URLs for the current page. * * @return array BCP-47 tag => URL. */ public function alternates(): array { if ( is_404() || is_search() || is_preview() ) { return array(); } $out = array(); if ( is_singular() ) { $id = (int) get_queried_object_id(); foreach ( Groups::translations( 'post', $id ) as $lang => $pid ) { if ( Languages::is_enabled( $lang ) && 'publish' === get_post_status( $pid ) ) { $out[ $lang ] = (string) get_permalink( $pid ); } } if ( ! $out ) { $out[ Groups::lang_of( 'post', $id ) ] = (string) get_permalink( $id ); } } elseif ( is_category() || is_tag() || is_tax() ) { $term = get_queried_object(); if ( $term instanceof \WP_Term ) { foreach ( Groups::translations( 'term', (int) $term->term_id ) as $lang => $tid ) { $link = get_term_link( $tid ); if ( Languages::is_enabled( $lang ) && ! is_wp_error( $link ) ) { $out[ $lang ] = $link; } } } } else { foreach ( Languages::all() as $lang ) { $out[ $lang ] = $this->router->language_url( $lang ); } } return (array) apply_filters( 'translateplus_hreflang', $out ); } public function hreflang(): void { $alts = $this->alternates(); if ( count( $alts ) < 2 ) { return; } echo "\n\n"; foreach ( $alts as $lang => $url ) { printf( '' . "\n", esc_attr( Languages::bcp47( $lang ) ), esc_url( $url ) ); } $default = $alts[ Languages::source() ] ?? reset( $alts ); printf( '' . "\n", esc_url( $default ) ); } }