Quick Dashboard Language Switch in the Admin Bar
Adds a language menu to the toolbar so each user can switch their own dashboard language in one click, using the languages installed on the site.
Opens WPIDE on
Code
add_action( 'admin_bar_menu', function ( $bar ) {
if ( ! is_admin() || ! is_user_logged_in() ) {
return;
}
$languages = get_available_languages();
if ( ! $languages ) {
return;
}
array_unshift( $languages, 'en_US' );
$current = get_user_locale();
$bar->add_node( array(
'id' => 'wpide-admin-lang',
'title' => esc_html( strtoupper( substr( $current, 0, 2 ) ) ),
'meta' => array( 'title' => __( 'Dashboard language' ) ),
) );
foreach ( array_unique( $languages ) as $locale ) {
$bar->add_node( array(
'parent' => 'wpide-admin-lang',
'id' => 'wpide-admin-lang-' . sanitize_key( $locale ),
'title' => esc_html( ( $locale === $current ? '✓ ' : '' ) . $locale ),
'href' => wp_nonce_url( add_query_arg( array( 'action' => 'wpide_set_admin_lang', 'locale' => $locale ), admin_url( 'admin-post.php' ) ), 'wpide_set_admin_lang' ),
) );
}
}, 80 );
add_action( 'admin_post_wpide_set_admin_lang', function () {
check_admin_referer( 'wpide_set_admin_lang' );
$locale = isset( $_GET['locale'] ) ? sanitize_text_field( wp_unslash( $_GET['locale'] ) ) : '';
if ( 'en_US' === $locale || in_array( $locale, get_available_languages(), true ) ) {
update_user_meta( get_current_user_id(), 'locale', 'en_US' === $locale ? 'en_US' : $locale );
}
wp_safe_redirect( wp_get_referer() ? wp_get_referer() : admin_url() );
exit;
} );
Notes
Changes only the current user's profile language; the site language stays the same.
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.