Using WordPress ‘is_rtl()’ PHP function

The is_rtl() WordPress PHP function determines whether the current locale is right-to-left (RTL).

Usage

if (is_rtl()) {
    // Execute RTL-specific code
}

Parameters

  • None

More information

See WordPress Developer Resources: is_rtl()

Examples

Enqueue RTL-specific styles and scripts

Load an RTL-specific CSS file and JavaScript file when the current locale is RTL.

if (is_rtl()) {
    wp_enqueue_style('style-rtl', get_template_directory_uri() . '/css/style-rtl.css');
    wp_enqueue_script('script-rtl', get_template_directory_uri() . '/js/script-rtl.js');
}

Add a CSS class for RTL layouts

Add a CSS class to the body tag for RTL-specific styling.

function add_rtl_body_class($classes) {
    if (is_rtl()) {
        $classes[] = 'rtl-layout';
    }
    return $classes;
}
add_filter('body_class', 'add_rtl_body_class');

Modify output for RTL text direction

Reverse the order of elements for RTL layouts.

if (is_rtl()) {
    $elements = array_reverse($elements);
}

Adjust the HTML attribute for RTL languages

Set the ‘dir’ attribute in the HTML tag based on the text direction.

function set_direction_attribute() {
    echo is_rtl() ? 'dir="rtl"' : 'dir="ltr"';
}
add_action('language_attributes', 'set_direction_attribute');

Switch menu positions for RTL layouts

Switch the primary and secondary menus for RTL layouts.

function switch_menus_rtl($args) {
    if (is_rtl()) {
        if ('primary' === $args['theme_location']) {
            $args['theme_location'] = 'secondary';
        } elseif ('secondary' === $args['theme_location']) {
            $args['theme_location'] = 'primary';
        }
    }
    return $args;
}
add_filter('wp_nav_menu_args', 'switch_menus_rtl');