Skip to main content
2 of 2
added 4 characters in body

How to Dynamically Switch WordPress Front Page Without Causing Canonical Redirect?

Question:

I'm trying to dynamically switch the front page of my WordPress site based on certain conditions (e.g., whether a user is logged in or not). I have two specific pages that I want to set as the front page dynamically.

Initially, I tried using the pre_option_page_on_front filter, but it causes issues with canonical URLs leading to redirects.

Here’s the code I used:

function dynamic_front_page($default) {
    $page_id_1 = 2; // Logged-in users' front page
    $page_id_2 = 10; // Not logged-in users' front page
    
    if (is_user_logged_in()) {
        return $page_id_1;
    } else {
        return $page_id_2;
    }
    return $default;
}

add_filter('pre_option_page_on_front', 'dynamic_front_page');

While this sets the front page correctly, it causes a canonical redirect issue.

How can I dynamically switch the front page without causing canonical redirect issues? Ideally, I’d like to achieve this using hooks and filters, without updating options in the database.