URL. */ declare( strict_types = 1 ); namespace AddBlack\Lang\Routing; defined( 'ABSPATH' ) || exit; use AddBlack\Lang\Settings\SettingsRepository; use AddBlack\Lang\Terms\TermTranslations; use AddBlack\Lang\Translation\PostTranslations; use WP_Post; use WP_Term; final class Alternates { public function __construct( private readonly Urls $urls, private readonly SettingsRepository $settings, private readonly PostTranslations $posts, private readonly TermTranslations $terms ) {} /** @return array lang => URL, published versions only. */ public function current_page(): array { $out = array(); if ( is_front_page() && 'page' === get_option( 'show_on_front' ) ) { foreach ( $this->posts->group( $this->urls->raw_option( 'page_on_front' ) ) as $lang => $id ) { if ( 'publish' === get_post_status( $id ) ) { $out[ $lang ] = $this->urls->lang_home( $lang ); } } return $out; } if ( is_search() ) { // Same search in every language: /?s=x, /uk/?s=x. foreach ( array_keys( $this->settings->get()->languages() ) as $lang ) { $out[ (string) $lang ] = add_query_arg( 's', rawurlencode( get_search_query( false ) ), $this->urls->lang_home( (string) $lang ) ); } return $out; } if ( is_home() && is_front_page() ) { // Latest posts on the front page: every language home is the same page. foreach ( array_keys( $this->settings->get()->languages() ) as $lang ) { $out[ (string) $lang ] = $this->urls->lang_home( (string) $lang ); } return $out; } if ( is_category() || is_tag() || is_tax() ) { $term = get_queried_object(); if ( $term instanceof WP_Term && $this->terms->is_translatable( $term->taxonomy ) ) { foreach ( $this->terms->group( $term->term_id ) as $lang => $id ) { $link = get_term_link( $id ); if ( is_string( $link ) ) { $out[ $lang ] = $link; } } } return $out; } if ( is_singular() ) { $post = get_queried_object(); if ( $post instanceof WP_Post && $this->settings->get()->is_translatable_type( $post->post_type ) ) { foreach ( $this->posts->group( $post->ID ) as $lang => $id ) { if ( 'publish' === get_post_status( $id ) ) { $out[ $lang ] = (string) get_permalink( $id ); } } } } return $out; } }