2017-08-01 67 views
1

我正在尝试向我的WordPress登录名添加跟踪,但功能current_user_can()wp_login动作中不起作用。这是我的代码:current_user_can无法在wp_login动作中工作

function track_logins() 
{ 
    error_log('tracking login'); 
    global $current_user,$wpdb; 
    $user_id = $current_user->ID; 
    $org_id = get_org_from_user ($user_id); 
    if(current_user_can("is_student")) 
    { 
     error_log('its a student'); 
     $record = $wpdb->insert(TABLE_TRACK,array(
      'user_id' => $user_id, 
      'org_id' => $org_id, 
      'date' => date('Y-m-d H:i:s'), 
      'type' => 'login' 

      ) 
     ); 
    } 
} 
add_action('wp_login', 'track_logins'); 

它显示第一个错误日志,但不是第二个。它不会进入if语句。

回答

1

我看了一下你的代码,可能有一个解决方案给你,但首先我要做一些假设,看看你的代码。

假设

1)你想检查用户的角色,看看他们是否有学生分配

2)get_org_from_user()是一个函数的地方在你的代码,如果无法将其删除从我的溶液

4.)TABLE_TRACK表名称被定义一些其中与表匹配刀片的输入

个功能的输入

1)的用户的用户名使用

$user_login 

2.)甲WP_User对象(约我们的信息登录用户)Codex Ref

$user 

解登录

function track_logins($user_login, $user) 
{ 
    // declare database 
    global $wpdb; 

    //not sure what this is? 
    $org_id = get_org_from_user ($user_id); 

    //I'm assuming you want to check the user role and 
    //check for user role 
    foreach($user->roles as $role){ 
     //replace role with the role you assigned to your students 
     if($role === 'administrator'){ 
      $wpdb->insert(TABLE_TRACK,array(
       'user_id' => $user->ID, 
       'org_id' => $org_id, 
       'date' => date('Y-m-d H:i:s'), 
       'type' => 'login' 
      ) 
     ); 
     } 
    } 
} 
add_action('wp_login', 'track_logins', 10, 2); 

wp_login挂钩

我加了10和2月底,对WordPress的抄本小记一下,干脆把套钩的优先级,所以我们可以得到WP_User对象传递给我们的函数 https://codex.wordpress.org/Plugin_API/Action_Reference/wp_login