Dynamically Setting the HTML Lang Attribute in WordPress Based on User Location

0

This guide details how to dynamically set the HTML `lang` attribute in a WordPress site based on user location and browser settings. This approach enables visitors from various regions to access the website more easily and enjoy a more user-friendly experience. Additionally, it explains how to save and apply the logged-in user’s language settings.

1. Introduction

We will explore how to set the HTML `lang` attribute according to the user’s location and preferred language to enhance website accessibility and user experience. This method helps provide better service to multinational users.

2. Setting Up the GeoLite2 Database

MaxMind’s GeoLite2 database is a tool that allows you to determine the user’s location based on their IP address. This database is available for free and provides sufficient basic location information.

  • Download the GeoLite2 database from MaxMind’s website.
  • Upload the downloaded `GeoLite2-Country.mmdb` file to the appropriate location on your server, such as the `wp-content` directory.

3. Downloading and Installing the GeoIP2 PHP Library

You can download and install the GeoIP2 PHP library directly without using Composer.

  • Download the GeoIP2 PHP library from MaxMind’s GitHub repository.
  • Extract the downloaded files into the `wp-content` directory.

4. Creating the GeoIP2 Library Autoload File

Create an autoloader file in the directory where you extracted the files to automatically load the PHP files.

// Create wp-content/GeoIP2/autoload.php file
spl_autoload_register(function ($class) {
    // Base directory for the project
    $base_dir = __DIR__ . '/src/';
    // Namespace prefix
    $prefix = 'GeoIp2\\';

    // If the class does not use the namespace prefix, move to the next registered autoloader
    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) {
        return;
    }

    // Get the relative class name
    $relative_class = substr($class, $len);

    // Replace the namespace prefix with the base directory, replace namespace separators with directory separators in the relative class name, append with .php
    $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';

    // If the file exists, require it
    if (file_exists($file)) {
        require $file;
    }
});

5. Writing a Function to Detect Browser Language and Set the Attribute

Write a function to detect the language from the user’s browser settings and set the HTML `lang` attribute accordingly.

// Modify functions.php file
require_once ABSPATH . 'wp-content/GeoIP2/autoload.php';
use GeoIp2\Database\Reader;

function get_browser_language($type = null) {
  $lang = 'en';
  if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
    $langs = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
    if (count($langs) > 0) {
      // Separate languages and quality factors into an array
      $lang = explode(';', $langs[0]);
      $lang = strtolower(substr($lang[0], 0, 2)); // Return the first two letters of the language code
    }
  }

  // Check for right-to-left languages
  $rtl_languages = ['ar', 'he', 'fa', 'ur'];
  $dir = in_array($lang, $rtl_languages) ? 'rtl' : 'ltr';

  if ($type == 'attribute') {
    return sprintf('lang="%s" dir="%s"', esc_attr($lang), esc_attr($dir));
  }

  return $lang; // Default
}

function get_user_language() {
  if (is_user_logged_in()) {
    $user_id = get_current_user_id();
    $user_lang = get_user_meta($user_id, 'user_language', true);
    if ($user_lang) {
      return $user_lang;
    }
  }
  return get_browser_language(); // Call browser language detection function
}

function set_html_lang_attribute() {
  echo '<html ' . get_browser_language('attribute') . '>';
}

// Add function to wp_head action in WordPress
add_action('wp_head', 'set_html_lang_attribute');

6. Adding Language Selection to User Profile

Add a language selection field to the user profile page so logged-in users can select their language settings.

// Add language selection to user profile page
function add_user_language_field($user) {
  ?>
  <h3>Language Settings</h3>
  <table class="form-table">
    <tr>
      <th><label for="user_language">Language</label></th>
      <td>
        <select name="user_language" id="user_language">
          <option value="en" <?php selected('en', get_the_author_meta('user_language', $user->ID)); ?>>English</option>
          <option value="ko" <?php selected('ko', get_the_author_meta('user_language', $user->ID)); ?>>Korean</option>
          <option value="fr" <?php selected('fr', get_the_author_meta('user_language', $user->ID)); ?>>French</option>
          <option value="ar" <?php selected('ar', get_the_author_meta('user_language', $user->ID)); ?>>Arabic</option>
          <option value="he" <?php selected('he', get_the_author_meta('user_language', $user->ID)); ?>>Hebrew</option>
          <option value="fa" <?php selected('fa', get_the_author_meta('user_language', $user->ID)); ?>>Persian</option>
          <option value="ur" <?php selected('ur', get_the_author_meta('user_language', $user->ID)); ?>>Urdu</option>
          <!-- Add other languages as needed -->
        </select>
      </td>
    </tr>
  </table>
  <?php
}
add_action('show_user_profile', 'add_user_language_field');
add_action('edit_user_profile', 'add_user_language_field');

function save_user_language_field($user_id) {
  if (!current_user_can('edit_user', $user_id)) {
    return false;
  }
  update_user_meta($user_id, 'user_language', $_POST['user_language']);
}
add_action('personal_options_update', 'save_user_language_field');
add_action('edit_user_profile_update', 'save_user_language_field');

7. Modifying header.php to Set the Lang Attribute

Modify the `header.php` file to set the HTML `lang` attribute.

<!DOCTYPE html>
<html <?php echo get_browser_language('attribute'); ?>>
<head>
    <!-- Header content -->
</head>
<body <?php body_class(); ?>>
    <!-- Body content -->
</body>
</html>

Conclusion

By following this guide, you can dynamically set the HTML `lang` attribute in WordPress based on the user’s location, browser settings, and logged-in user’s preferences. This allows visitors from various regions to access your website more easily and enjoy a more user-friendly experience. Utilizing the GeoLite2 database and GeoIP2 PHP library to detect user location and adding a language selection feature to the user profile page can significantly enhance user experience.

Leave a Reply