我想根据登录的用户更改首页。
如果User\\u Bob已登录,则首页为;“Bob”;[邮编:123]。如果User\\u Jane登录到首页,则为;“简”;[邮编:555]。如果没有用户登录,则首页为;“主要”;[职位编号:222]。
许多其他解决方案建议更改选项,如:
update_option( \'page_on_front\', $x->ID );
update_option( \'show_on_front\', \'page\' );
然而,这是不可行的,因为我想对每个用户的每个页面请求都这样做。还是我错了,这是一个很好的技巧?
我觉得在用户登录后修改主查询是一个更好的选择,但我不确定应该使用哪些挂钩。
How can I override the main query after the user is logged in, to redirect to a specific page ID?
最合适的回答,由SO网友:Ben HartLenn 整理而成
您可以修改静态首页上的主查询,根据登录用户的不同切换到不同的页面,方法如下:
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]);
}
}
});
然后,静态首页设置被单独保留在自定义设置之外。