Change ISO code for language on single page

On my forum we have created a section for Chinese Posts. Everything is working as desired, however the ISO code for the pages still shows English as that is the site setting. Does anyone know if there is a way we can set the category or individual pages to show that they are a different language?

Interesting, what are your thoughts on this @sam

I have not been able to see a way to change this in the existing software. Anyone have an idea if this could be built? I think it could help with traffic on our site as well as many others that have additional languages on one instance. Any direction would be helpful!
-Robert

Not that I’m an expert or anything, but shouldn’t that be possible with JavaScript or something similar?

I agree that it should be possible. I am trying to find a solution or suggestion on how I might implement this as we have multiple languages and I am not sure how I change the language code when someone posts in the Chinese category, however leave it as english when in the other categories. I also want to make sure this is not going to cause any issues elsewhere if we try to implement it. I know there are other forums that run multiple languages, however it looks like all the ones that run more than one language all show an “en” source code when you look at non english pages. Only the forums that are based in another language change. From my limited understanding this will mean that information is harder to find on google and if an english speaking person finds my chinese content google will not offer to translate as it shows english.
-Robert

Unfortunately this isn’t a built-in feature of Discourse. Theme components (javascript) wouldn’t work either, because the page language is set way before any javascript is loaded.

Having separate languages per-category would technically be possible using a plugin. This would work for crawlers like google, and would also trigger browser auto-translation features.

One issue with this is that Discourse is a ‘single page application’, and browsers only seem to check the lang attribute on the initial page load. That means that a user browsing the forum will be ‘stuck’ on the language of the first page they viewed. That may or may not be an issue depending on your use case.

I think the SEO and initial translation benefits of seeing it on a search would outweigh any issues I am seeing once on the forum. I am certainly interested in speaking with someone on what it might take to get this made and what it would look like currently and what might be needed if in the future we add more languages. Would the plugin be set per category or per post etc.
-Robert

Having done some further experimentation, this might not be completely true. Googlebot does render simple javascript when crawling the web, so we should be able to use javascript to modify the language.

To change the language for topics in a specific category (and its sub-categories), you can add something like this to the </head> section of a theme:

<script>
	if(document.querySelector("#breadcrumb-0 a[href='/c/chinese']")){
		document.documentElement.lang = "zh"
    }
</script>

I can’t find any specific documentation from google about whether this is acceptable, but I can see that it works when I “fetch as googlebot”:

@Robert_Fay let us know if you would like a hand adding this to your site.

I’m a bit confused, in looking at the code, there is no #breadcrumb-0 on our page.

image

I had tried using

<script>
if(document.querySelector("a.bullet[href='/c/chinese']")){
	document.documentElement.lang = "zh"
}
</script>

but that didn’t seem to do the trick. I have a feeling those elements are loaded later, because the code works in in the browser console, but not in a component /head. Any pointers?

This code is specifically for the crawler view of the site which googlebot sees. It has a different html structure to the regular view.

If you change your browser’s user agent to googlebot then you will see it take effect.

David,

I am still not seeing the change even as google bot. Could the issue be that my category name is actually 中文 技术论坛 and we use chinese as a category slug? Here is the page

 https://forum.digikey.com/c/chinese

中文論壇 - DigiKey TechForum - An Electronic Component and Engineering Solution Forum
Thank you
-Robert

Ah, I should have specified that the code needs to go in the </body> section of the theme. Alternatively, you can leave it in the </head>, and wrap it like this:

<script>
    document.addEventListener('DOMContentLoaded', function(){
    	if(document.querySelector("#breadcrumb-0 a[href='/c/chinese']")){
    		document.documentElement.lang = "zh";
    	}
    });
</script>

If you would also like the <html lang= to be updated for non-googlebot views, you can add this. Google chrome doesn’t seem to detect the ‘live’ change in language, but other browsers might:

<script type="text/discourse-plugin" version="0.8">
    api.onPageChange(()=>{
        const body = document.documentElement.querySelector("body");
        if(body.classList.contains("category-chinese")){
            document.documentElement.lang = "zh";
        }else{
            document.documentElement.lang = I18n.locale;
        }
    });
</script>

This is in and looks like it is working in the googlebot views.
Thank You for all the help!
-Robert

안녕하세요, @david

최근 감사 작업을 하던 중 중국어, 스페인어, 히브리어 카테고리에 사용되는 이 코드 조각이 간헐적으로만 작동하는 것을 발견했습니다. 현재 이 코드가 정상 작동하는 페이지들만 콘솔에 오류가 표시되고 있으며, 오류가 없는 페이지들은 이제 검색 위원회(search council)에서 영어 페이지로 표시됩니다. 혹시 의견이 있으신가요?

아래는 해당 오류입니다.

사용 중인 중국어 카테고리 코드입니다.

<script>
    document.addEventListener('DOMContentLoaded', function(){
    	if(document.querySelector("#breadcrumb-0 a[href='/c/chinese']")){
    		document.documentElement.lang = "zh";
    	}
    });
</script>

간단히 말씀드리면, 오류가 있는 페이지에서 라이브 테스트를 수행하면 오류는 사라지지만, 페이지가 중국어에서 스페인어로 표시되던 것이 영어 페이지로 표시됩니다.
-로버트

data-vocabulary.org 경고는 최신 버전의 discourse에서 해결되어야 합니다.

귀하의 사이트에는 이 업데이트가 적용되어 있으므로, 이제 구글봇이 이를 반영할 때까지 기다리면 됩니다. 확인하신 대로 라이브 테스트를 수행하면 경고가 해결됩니다.

불행히도 이 브레드크럼(breadcrumbs) 재구조화로 인해 우리가 만든 작은 언어 스크립트가 깨졌습니다. 브레드크럼에 더 이상 #breadcrumb-0 ID가 없으므로 다른 방법이 필요합니다. 다음 코드가 문제를 해결할 것 같습니다:

<script>
    document.addEventListener('DOMContentLoaded', function(){
    	if(document.querySelector("#breadcrumbs a[href*='/c/chinese']")){
    		document.documentElement.lang = "zh";
    	}
    });
</script>

라이브 테스트로 문제가 해결되는지 알려주세요.

이 방법은 중국어 카테고리의 항목에 대해서는 문제를 해결하는 것 같았지만, 하위 카테고리에서는 작동하지 않습니다. 예를 들어 /c/chinese/FAQ의 경우 별도의 설정이 필요할까요?

-Robert

음, 하위 카테고리에서도 작동해야 합니다. 이 토픽을 googlebot으로 가져오면 lang=zh 메타데이터가 반환됩니다.

시도하신 토픽이 Google에 캐시된 것일 수도 있습니다. 또한 이 스크립트는 카테고리 페이지 자체에서는 작동하지 않고 토픽에서만 작동한다는 점도 기억해 두세요.

첫 번째 테스트에서 무슨 일이 있었는지 정확히 알 수 없습니다. 몇 개의 하위 카테고리 페이지를 더 작업했는데, 모두 정상적으로 작동하고 있습니다.

시간 내어 주셔서 다시 한번 감사합니다.
-Robert

안녕하세요 @david
SEO 팀과 함께 사이트를 검토하던 중, 해당 링크들이 더 이상 작동하지 않는 것 같습니다.

독일어 카테고리 내 게시글 예시입니다.

Google Search Console에서 크롤링된 페이지를 확인해 보면 영어로 표시되고 있습니다.

현재 사용하고 있는 코드는 다음과 같습니다.

<script>
    document.addEventListener('DOMContentLoaded', function(){
    	if(document.querySelector("#breadcrumbs a[href*='/c/german']")){
    		document.documentElement.lang = "de";
    	}
    });
</script>

도움이나 방향을 제시해 주시면 감사하겠습니다.
-Robert