Set a Different Language for Individual Pages
Adds a "Page language" box to the editor so a single post or page written in another language gets the correct lang attribute (and text direction) for screen readers, spell checkers and search engines.
Opens WPIDE on
Code
$wpide_rtl_langs = array( 'ar', 'he', 'fa', 'ur', 'ps', 'yi', 'dv', 'ckb' ); // Codes written right-to-left.
add_action( 'init', function () {
foreach ( array( 'post', 'page' ) as $type ) {
register_post_meta( $type, '_wpide_lang', array(
'type' => 'string',
'single' => true,
'show_in_rest' => true,
'sanitize_callback' => function ( $value ) {
return preg_match( '/^[a-zA-Z]{2,3}(-[a-zA-Z0-9]{2,8})*$/', (string) $value ) ? $value : '';
},
'auth_callback' => function ( $allowed, $key, $post_id ) {
return current_user_can( 'edit_post', $post_id );
},
) );
}
} );
add_action( 'add_meta_boxes', function () {
add_meta_box( 'wpide-lang', __( 'Page language' ), function ( $post ) {
wp_nonce_field( 'wpide_lang_save', 'wpide_lang_nonce' );
printf(
'<label for="wpide_lang" class="screen-reader-text">%1$s</label><input type="text" id="wpide_lang" name="wpide_lang" value="%2$s" placeholder="%3$s" style="width:100%%"><p class="description">%4$s</p>',
esc_html__( 'Language code' ),
esc_attr( get_post_meta( $post->ID, '_wpide_lang', true ) ),
esc_attr( str_replace( '_', '-', get_locale() ) ),
esc_html__( 'Leave empty to use the site language.' )
);
}, array( 'post', 'page' ), 'side' );
} );
add_action( 'save_post', function ( $post_id ) {
if ( ! isset( $_POST['wpide_lang_nonce'] ) || ! wp_verify_nonce( sanitize_key( $_POST['wpide_lang_nonce'] ), 'wpide_lang_save' ) || ! current_user_can( 'edit_post', $post_id ) ) {
return;
}
$value = isset( $_POST['wpide_lang'] ) ? sanitize_text_field( wp_unslash( $_POST['wpide_lang'] ) ) : '';
if ( '' === $value ) {
delete_post_meta( $post_id, '_wpide_lang' );
} else {
update_post_meta( $post_id, '_wpide_lang', $value );
}
} );
add_filter( 'language_attributes', function ( $output ) use ( $wpide_rtl_langs ) {
if ( is_admin() || ! is_singular() ) {
return $output;
}
$lang = get_post_meta( get_queried_object_id(), '_wpide_lang', true );
if ( ! $lang ) {
return $output;
}
$dir = in_array( strtolower( strtok( $lang, '-' ) ), $wpide_rtl_langs, true ) ? 'rtl' : 'ltr';
return sprintf( 'dir="%1$s" lang="%2$s"', esc_attr( $dir ), esc_attr( $lang ) );
} );
Notes
Enter a language code such as fr, de-CH or ar. RTL languages also set dir="rtl".
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.