Different home page for logged off users

I creating website and I need to have different homepages for logged in and logged off users. I have page 'Home page' which is set as home page and is filled with information about my site and pictures and simple page 'Home logged in' which was set as BuddyPress activity stream. What I need is: - User A is visiting website but he is not logged in and can see 'Home page' as homepage - User B is visiting website and he is logged in and can see 'Home page logged in' as homepage. I have tried to reach it with this code, by inserting it to my theme functions.php :

function switch_homepage() {
if ( is_user_logged_in() ) {
    $page = get_page_by_title( 'Home page logged in' );
    update_option( 'page_on_front', $page-ID );
    update_option( 'show_on_front', 'page' );
} else {
    $page = get_page_by_title( 'Home page' );
    update_option( 'page_on_front', $page-ID );
    update_option( 'show_on_front', 'page' );
}
}
add_action( 'init', 'switch_homepage' );

But this code sometimes when refreshing page or logging off started to show 'Home page logged in' for logged off users. As I readed this happening because this code change homepage in database. So now my question is how to have separate home page for logged off users without changing database every time?

Topic switch php homepage Wordpress

Category Web


I am currently using the following code to display a different homepage for logged in and logged out users. You simply need to change the page id to your chosen page within wordpress and add this to your functions.php file:

function switch_homepage() {
    if ( is_user_logged_in() ) {
        $page = 898; // for logged in users
        update_option( 'page_on_front', $page );
        update_option( 'show_on_front', 'page' );

    } else {
        $page = 615; // for logged out users
        update_option( 'page_on_front', $page );
        update_option( 'show_on_front', 'page' );
    }
}
add_action( 'init', 'switch_homepage' );

I would like to set a different homepage by user role however am struggling to get the solution I need.


Can you use this to redirect the logged out users?

<?php if ( !is_user_logged_in() { ?>
<?php wp_redirect( 'https://yourdomain.com.au/logoutpage', 302 ); exit; ?>
<?php } ?>

or this solution? setting a specific home page for logged in users

About

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