Is there a problem with the code?
Your code is already properly adding the lang query variable to the homepage URL. But you need to understand these points:
-
On the homepage URL becomes
http://localhost/mywebsitename/?lang=enwhich should be ok$wp->requestis empty on the homepage, hence the above URL is expected. And you could useget_queried_object()->post_nameto force the Page’s slug be in that URL, but WordPress would actually redirect you to the URL without that slug, because the Page is set as the static front page, which means the content atexample.comandexample.com/page-slug/are identical and thus WordPress performs a (canonical) redirect when loading the latter URL. -
but supposedly it tries to load
index.phpinstead ofpage.php, which generally wouldn’t be a problem but in that case some things likeis_front_page()don’t behave as it shouldNo, WordPress will try to load
front-page.php,home.phporpage.phpbefore falling back to the index template. But even if the index template is used,is_front_page()would still behave properly — remember that the query determines the template and not the other way round.So one could say that “if
is_front_page()returns true,page.phpmight be used”, but this is incorrect: “ifindex.phpis used,is_front_page()would return false”.