簡體   English   中英

如何將未登錄的用戶重定向到Wordpress中的其他頁面

[英]How to redirect a user not logged in to a different page in wordpress

我想將未登錄的用戶重定向到我創建的登錄頁面。我在主題的functions.php中編寫了代碼,但似乎不起作用。

<?php 
if (is_page($page = 'private-gallery' )) {
 if (!is_user_logged_in() ) {
 template_redirect ('http://www.site.it/wp/private-area' );
 exit;
 }
}
?>

您可以通過掛接到template_redirect [ 操作參考 ]來實現。 (請注意,您也可以使用較早執行的鈎子,但是為了方便起見,我主要使用它)。

這樣,您可以檢索當前的帖子,並以此為基礎進行語句比較,以查看當前頁面是否為private-gallery

在以下方法中, wp_redirect() [ 函數參考 ]用於重定向到正確的頁面。 home_url() [ 函數參考 ]用於檢索當前站點的主頁URL(始終嘗試避免使用完整路徑URL)。

wp_redirect基本上執行header("Location: $location", true, $status); 其中$status默認為302

add_action('template_redirect', 'gianni_private_gallery_redirect');
function gianni_private_gallery_redirect(){
    global $post;
    if($post){
        if( $post->post_name=='private-gallery' ) {
            if ( !is_user_logged_in() ) {
                // By default a 302 redirect.
                // Add your custom status code as second parameter if required.
                wp_redirect( home_url( '/private-area/' ) ); 
                exit;
            }
        }
    }
}

暫無
暫無

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

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