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.
home.php
orfrontpage.php
and the answer would be to use anif ( is_user_logged_in() ) { get_template_part( .. logged in template ... ); } else { get_template_part( ...logged out template... ); }
, but it sounds like you've chosen to use a page builder instead. That doesn't mean what you need can't be done, but this particular method of filtering the option that you've chosen won't be easy to fix. Just because you want the contents of that page to show on the frontpage, doesn't mean that page has to be the frontpage