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' );

?

Topic home-url frontpage Wordpress

Category Web


If you're just trying to display different content to logged-in vs. logged-out users, I'd recommend using the the_content filter.

add_filter( 'the_content', 'wpse_387084_content_selector' );
function wpse_387084_content_selector( $content ) {
    if ( is_front_page() && is_user_logged_in() ) {
        $page = get_post( 2516 );
        $content = $page->post_content;
    }
    return $content;
}

The above code assumes that you've set the "Page on Front" to the page with ID 2, and that's what you want to show to unauthenticated users.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.