Link to the Current-Language Version of Any Page
Adds a [wpide_wpml_link id="123"] shortcode that links to the translation of a page in the language being viewed, using that translation's title, so internal links never send visitors to the wrong language.
Opens WPIDE on
Code
add_shortcode( 'wpide_wpml_link', function ( $atts ) {
$atts = shortcode_atts( array( 'id' => 0, 'text' => '' ), $atts, 'wpide_wpml_link' );
$id = absint( $atts['id'] );
if ( ! $id || ! get_post( $id ) ) {
return '';
}
if ( defined( 'ICL_SITEPRESS_VERSION' ) ) {
$id = (int) apply_filters( 'wpml_object_id', $id, get_post_type( $id ), true );
}
if ( 'publish' !== get_post_status( $id ) ) {
return '';
}
return sprintf( '<a href="%1$s">%2$s</a>', esc_url( get_permalink( $id ) ), esc_html( '' !== $atts['text'] ? $atts['text'] : get_the_title( $id ) ) );
} );
Notes
Add text="..." to set your own link text (it can be translated with the page). Falls back to the original page if there is no translation.
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.