簡體   English   中英

Wordpress掛鈎可對用戶進行身份驗證以獲取預定義的URL

[英]Wordpress hook to authenticate user for pre-defined URLs

我正在構建一個包含許多前端編輯頁面的相當復雜的項目。 例如,全部從前端添加/編輯/列出自定義帖子類型,編輯個人資料等。

目前,我當然可以檢查用戶是否在每個前端登錄牆頁面上登錄。 但是,這似乎是解決此問題的一種不好的方法,因為我將在許多頁面上使用相同的條件,因此會有很多重復的代碼。

我在想,也許有更好的方法可以基於某些掛鈎(我找不到)進行身份驗證。 我希望我可以做這樣的事情:

# 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;
}

參考

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM