0

I want to change the front page based on who is logged in.

If User_Bob is logged in, the front page is "Bob" [post id: 123]. If User_Jane is logged in the front page is "Jane"[post ID: 555]. If no user is logged in, the front page is "Main"[post ID:222].

Many other solutions recommend changing options like:

update_option( 'page_on_front', $x->ID );
update_option( 'show_on_front', 'page' );

However, this isn't feasible, since I want to do it on every page request with every user. Or am I incorrect, and this is a perfectly good technique?

I feel like modifying the main query after the user is logged in is a better option, but I'm not sure which hooks I should use.

How can I override the main query after the user is logged in, to redirect to a specific page ID?

0

1 Answer 1

1

You could modify the main query on your static front page to switch to different pages depending on the logged in user by doing something like this:

add_action('pre_get_posts', function($query) {
    // if not admin, and if it is the main query, and the page id matches the page id set to be static front page...
    if ( ! is_admin() && $query->is_main_query() && $query->get('page_id') == get_option('page_on_front') ) {
        // ...Check if user is logged in
        if ( is_user_logged_in() ) {
            // ...Maybe create a handy array where user ids are keys, and matching page ids are the values
            $users_pages_ids_array = [
                3 => 23,
                5 => 25,
                7 => 31
            ];
            // store the currently logged in users id
            $current_user_id = get_current_user_id();
            // load the page that is matched with user
            $query->set('page_id', $users_pages_ids_array[$current_user_id]);
        }
    }
});

Then the static front page setting is left alone outside of your customization's.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.