Halloween Sale 15% off Ends in See the plans
PHP

"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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.