0

I want to add lang query variable to existing URL.

I have registered query variable:

add_filter('query_vars', 'custom_add_query_vars');
function custom_add_query_vars($vars){
    $vars[] = "lang";
    return $vars;
}

The following code works good everywhere but not when I'm currently on the home page.

<?php global $wp; ?>
<a href="<?php echo add_query_arg(array('lang' => 'en'), $wp->request); ?>">English</a>

Is there a problem with the code? On the homepage URL becomes http://localhost/mywebsitename/?lang=en which should be ok but supposedly it tries to load index.php instead of page.php, which generally wouldn't be a problem but in that case some things like is_front_page() don't behave as it should.

Static page is set as a homepage under Settings->Reading and pretty permalinks are active ("Post name" option).

1 Answer 1

0

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:

  1. On the homepage URL becomes http://localhost/mywebsitename/?lang=en which should be ok

    $wp->request is empty on the homepage, hence the above URL is expected. And you could use get_queried_object()->post_name to 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 at example.com and example.com/page-slug/ are identical and thus WordPress performs a (canonical) redirect when loading the latter URL.

  2. but supposedly it tries to load index.php instead of page.php, which generally wouldn't be a problem but in that case some things like is_front_page() don't behave as it should

    No, WordPress will try to load front-page.php, home.php or page.php before 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.php might be used", but this is incorrect: "if index.php is used, is_front_page() would return false".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.