我正在构建一个相当复杂的项目,该项目有许多前端编辑页面。例如,添加/编辑/列出自定义帖子类型、编辑配置文件等,所有这些都来自前端。
目前,我当然可以检查用户是否登录到每个前端登录墙页面。然而,这似乎是解决这个问题的一种糟糕方法,因为我在许多页面上都会有相同的条件,因此会有很多重复的代码。
我在想,也许有一种更好的方法可以基于某个钩子(我找不到)进行身份验证。我希望我能做一些类似的事情:
# create array of URLs where login is required
$needLoginArr = array(url1, url2, url3, ...)
# If current requested URL is in above array, then redirect or show different view based on whether or not user is logged in
在未来,由于我计划在不同的插件中集成,所以在每个页面上设置条件可能是不现实的,所以使用URL进行身份验证会很有用。
我可能错过了什么,所以如果有更好的方法,请告诉我。
感谢
您可以将页面ID列表添加到一个选项中:
$need_login = array(
'page1',
'page1/subpage',
'page2',
// and so forth
);
$need_login_ids = array();
foreach( $need_login as $p ) {
$pg = get_page_by_path( $p );
$need_login_ids[] = $pg->ID;
}
update_option( 'xyz_need_login', $need_login_ids );
然后,检查您的页面是否在$need_login
组中:
add_filter( 'the_content', 'so20221037_authenticate' );
function so20221037_authenticate( $content ) {
global $post;
$need_login_ids = get_option( 'xyz_need_login' );
if( is_array( $need_login_ids ) && in_array( $post->ID, $need_login_ids ) ) {
if( is_user_logged_in() ) {
// alter the content as needs
$content = 'Stuff for logged-in users' . $content;
}
}
return $content;
}
参考文献
get_page_by_path()
is_user_logged_in()
update_option()
get_option()