WordPress.org

Support

Support » Plugins and Hacks » Automatically switch WordPress language based on User's Browser Language

Automatically switch WordPress language based on User's Browser Language

  • Hello Takayuki,

    what’s your recommended way to automatically switch to a user preferenced language based on Browser settings?

    In my case I the website is in German and English.
    When a user prefers German by his browser settings, the site should be initially displayed in German. If not (English, Spanish or any other language), the English translation should be automatially displayed.

    I would be thankful for a solution on that.
    Dan

    https://wordpress.org/plugins/bogo/

Viewing 4 replies - 1 through 4 (of 4 total)
  • Plugin Author Takayuki Miyoshi

    @takayukister

    Bogo has a function bogo_http_accept_languages() that returns an array of languages that the user can accept, in the user’s preference order, but it isn’t actually used in Bogo.

    You can use the function to get the most preferred language (the first one in the array). The last thing you need to do is redirecting to the translated page in the language.

    But it is not so simple because it’s uncertain if there is a translation of the current page. About that, you can use bogo_language_switcher() function defined in includes/link-template.php as a reference.

    1. Find right hook before site is rendered
    2. Check if the site is the users entry point (the rewrite should not happen when the user intentionally switched the language by a link)
    3. If it’s the entry point: check if the current translation is the closest available in comparison with bogo_http_accept_languages()
    4. If other URL found do the URL rewrite

    Any quick ideas for 1, 2 (maybe using HTTP-REFERER) and 4?
    I already wrote 3 for the menu switch language item.

    PS: I think this would be a nice feature for Bogo to find the closest translation and automatically switch to this URL. It would improve the UX

    Plugin Author Takayuki Miyoshi

    @takayukister

    Find right hook before site is rendered

    The template_redirect action hook would fit.

    Check if the site is the users entry point (the rewrite should not happen when the user intentionally switched the language by a link)

    Checking the HTTP-REFERER header is the best, but HTTP-REFERER is not reliable.

    If other URL found do the URL rewrite

    You can use wp_safe_redirect().

    I think this would be a cool feature (loading the language site in the user’s browser preferences by default). Did anyone actually try out code in their theme’s functions.php yet? I’d love to see an actual code snippet so I don’t have to figure it all out myself…

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Automatically switch WordPress language based on User's Browser Language’ is closed to new replies.