【问题标题】:Redirect if it's not certain user - wordpress如果不是特定用户则重定向 - wordpress
【发布时间】:2017-09-22 11:23:42
【问题描述】:

我在 wordpress 中为某个用户创建了一个页面。假设他的用户名是 John。我正在寻找只允许“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

【问题讨论】:

  • 用户名是“John”还是“john”?
  • @luweiqi 是“约翰”
  • 试试echo $username;看看是什么
  • 如果@luweiqi 回答有效,则接受回答

标签: php wordpress


【解决方案1】:

您可以改用wp_get_current_user() 函数。

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

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

【讨论】:

  • 它正在重定向所有用户。我已经仔细检查过,用户名“John”的用户也被重定向了!
  • @user6176114 尝试回显$username 变量
  • 我尝试回显 $username 并显示“John”。所以用户名肯定是正确的。
  • 谢谢它现在工作了。我不得不将此添加到您的代码中 global $current_user; get_currentuserinfo();
【解决方案2】:

这可能会解决您的问题。

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/

【讨论】:

  • 它根本不工作。现在它甚至没有重定向。
  • @user6176114 再试一下,我已经修改了。
  • 你能不能稍微解释一下你的情况。请尝试 add_action('init', 'blockusers_init');功能 blockusers_init() { $current_user = wp_get_current_user(); var_dump( $current_user ->user_login );出口; } 并告诉我你得到了什么。 * 请发布准确的输出。
  • 您的代码正在重定向所有用户。但是下面的代码对我有用。 global $current_user; get_currentuserinfo(); $username = $current_user-&gt;user_login; if ( $username == 'John' ) { echo ''; } else { wp_redirect( home_url() ); exit; }
【解决方案3】:

试试这个:首先检查用户是否登录,如果是,然后获取用户信息并使用它做任何你想做的事情

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('/'));

注意:请务必检查您在数据库中的用户名,我将用户名设置为我的姓氏。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多