"Also Available In" Links Above Polylang Posts
Shows a short line above each post or page listing the other languages it has been translated into, with links, so visitors who arrive in the wrong language can switch straight away.
Opens WPIDE on
Code
$wpide_label = 'Also available in:'; // Text before the links.
add_filter( 'the_content', function ( $content ) use ( $wpide_label ) {
if ( is_admin() || ! is_singular() || ! in_the_loop() || ! is_main_query() || ! function_exists( 'pll_get_post_translations' ) ) {
return $content;
}
$current = pll_current_language();
$translations = pll_get_post_translations( get_the_ID() );
$names = array_combine( pll_languages_list( array( 'fields' => 'slug' ) ), pll_languages_list( array( 'fields' => 'name' ) ) );
$links = array();
foreach ( $translations as $slug => $post_id ) {
if ( $slug === $current || 'publish' !== get_post_status( $post_id ) ) {
continue;
}
$links[] = sprintf( '<a href="%1$s" hreflang="%2$s" lang="%2$s">%3$s</a>', esc_url( get_permalink( $post_id ) ), esc_attr( $slug ), esc_html( isset( $names[ $slug ] ) ? $names[ $slug ] : strtoupper( $slug ) ) );
}
if ( ! $links ) {
return $content;
}
$label = function_exists( 'pll__' ) ? pll__( $wpide_label ) : $wpide_label;
return '<p class="wpide-pll-available">' . esc_html( $label ) . ' ' . implode( ', ', $links ) . '</p>' . $content;
} );
Notes
Hidden when the post has no translations. Change $wpide_label, or register it as a Polylang string to translate it.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.