我正在构建一个包含许多前端编辑页面的相当复杂的项目。例如,从前端添加/编辑/列出自定义帖子类型,编辑个人资料等等。
目前,我当然可以检查用户是否登录每个前端登录壁页面。然而,这似乎是解决这个问题的一种不好的方法,因为我在许多页面上都有相同的条件,因此有很多重复的代码。
我想也许有一种更好的方法,我可以根据一些钩子(我找不到)进行身份验证。我希望我可以这样做:
# 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进行身份验证会很有用。
我可能在这里遗漏了一些东西,所以如果有更好的方法请告诉我。
由于
答案 0 :(得分:0)
您可以将页面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;
}