簡體   English   中英

重定向,如果它不確定用戶 - wordpress

[英]Redirect if it's not certain user - wordpress

我在wordpress中為某個用戶創建了一個頁面。 假設他的用戶名是約翰。 我正在尋找只允許'John'訪問該頁面的PHP腳本,如果用戶名不同於'John'的用戶試圖訪問該頁面,他們會被重定向到另一個頁面。

我是PHP的新手,所以這里有一些我試過的代碼。 但它重定向所有用戶,甚至用戶名為'John'的用戶

<?php $user_info = get_userdata(1);
  $username = $user_info->user_login;
if ( $username=='John' ) {
echo '';
} else {
wp_redirect( home_url() );
exit;
}
?>

這是一個帶有參數的wordpress頁面,用於獲取用戶數據 - https://codex.wordpress.org/Function_Reference/get_userdata

您可以使用wp_get_current_user()函數。

global $current_user; 
get_currentuserinfo();
$username = $current_user->user_login;

if ( $username == 'John' ) {
    echo '';
} else {
    wp_redirect( home_url() );
    exit;
}

這可以解決您的問題。

add_action( 'init', 'blockusers_init' );
function blockusers_init() {
  global $current_user; 
  $current_user = wp_get_current_user();
  if ( 'John' == $current_user->user_login ) {
    //your desire page url
    wp_redirect( 'your page url' );
    exit;
  } else {
     wp_redirect( home_url() );
     exit;
  }
}

參考

add_action( 'init', 'blockusers_init' );
function blockusers_init() {
  if ( is_admin() && ! current_user_can( 'administrator' ) &&
 ! ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) {
    wp_redirect( home_url() );
    exit;
 }
}

https://premium.wpmudev.org/blog/limit-access-to-your-wordpress-dashboard/

試試這個:首先檢查用戶是否登錄_如果是,則獲取用戶信息並隨意執行任何操作

if(is_user_logged_in()){
  $current_user = wp_get_current_user();
      if($current_user->user_login == "John"){
             wp_safe_redirect("Where ever you want");
             exit;
           }
      else
          wp_safe_redirect(home_url('/'));

注意 :確保在數據庫中檢查您的用戶名,我將用戶名設置為我的姓氏。

暫無
暫無

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

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