Problem with language detection

Hey folks,

I have a problem with the language detection, which I can’t get set up properly.
First i realized, that it did not work on my project with three different languages.
After testing around and not get it working, I downloaded a fresh langkit and tried the language detection there. Same result, it always shows me the default language after the first request.
When i print out $site->detectedLanguage(); in the fresh langkit it always shows me “en”, even if my browser and OS is set to german.
Does anyone have an idea what could be the cause of this or how I could debug this more?
Many thanks!

So I could find out a bit more in between… :slight_smile:
My config looks as following:

c::set('languages', array(
  array(
    'code'    => 'de-ch',
    'name'    => 'Deutsch',
    'default' => true,
    'locale'  => 'de_CH',
    'url'     => '/',
  ),
  array(
    'code'    => 'en-us',
    'name'    => 'English',
    'locale'  => 'en_US',
    'url'     => '/en',
  ),
  array(
    'code'    => 'fr-ch',
    'name'    => 'Français',
    'locale'  => 'fr_CH',
    'url'     => '/fr',
  ),
));

The problem seems to be in my language codes… When I use for e.g. just “de” instead of “de-ch”, then the detection works just fine.
Isn’t it possible to use language codes with locales as “code”?
I did it like this, because I want the correct locale to appear in my hreflang tags…
Hopefully someone can help this time… :slight_smile: Thanks in advance!

Check out this post: Language detection with locale variations not working (en_US, en_GB)

thank you! so this basically means, it’s not possible to use language codes with locales for now.

Looks like it. A workaround could be your own language detection workflow.

I think i’ll leave that to you, the pro’s. :slight_smile:

I think I found another workaround where I do not have to touch the kirby core stuff.
Here’s my solution, in case it might help someone else with the same issue.

In the config I changed the code to the unlocalized version (e.g. “de” instead of “de-ch”):

c::set('languages', array(
  array(
    'code'    => 'de',
    'name'    => 'Deutsch',
    'default' => true,
    'locale'  => 'de_CH',
    'url'     => '/',
  ),
  array(
    'code'    => 'en',
    'name'    => 'English',
    'locale'  => 'en_US',
    'url'     => '/en',
  ),
  array(
    'code'    => 'fr',
    'name'    => 'Français',
    'locale'  => 'fr_CH',
    'url'     => '/fr',
  ),
));

And in my header part, where i output the hreflang-tags, I used the locale instead of the code.
To make it work fine for google, you just needed to replace the underline with a dash there:

<?php
foreach($site->languages() as $language):
  if($language == $site->language()) continue;
  $localeWithDash = str_replace("_","-",$language->locale());
?>
<link rel="alternate" hreflang="<?= $localeWithDash ?>" href="<?php echo $page->url($language->code()) ?>" />
<?php endforeach ?>