最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Set front_page programatically after user login via query, while leaving site option alone

programmeradmin1浏览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?

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?

Share Improve this question asked Feb 5, 2022 at 17:12 John DeeJohn Dee 5135 silver badges14 bronze badges 0
Add a comment  | 

1 Answer 1

Reset to default 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.

发布评论

评论列表(0)

  1. 暂无评论