Different front page for logged in and logged out user but the same URL in Wordpress
I have two home pages created in WP. One is set as the front page but for only logged-out users. For logged-in users, they see home page 2 as their home page.
However, I want the URL for logged-in users to be the default URL of my site. So a mere redirection doesn't work as I will have site.com/home-2.
Is there a way I could achieve this? The code below came across doesn't work and breaks my site.
unction switch_homepage() {
if ( is_user_logged_in() ) {
$page = 2516; // for logged in users
update_option( 'page_on_front', $page );
update_option( 'show_on_front', 'page' );
} else {
$page = 2; // for logged out users
update_option( 'page_on_front', $page );
update_option( 'show_on_front', 'page' );
}
}
add_action( 'init', 'switch_homepage' );
?