0

I want to get the current user id from inside my plugin and use it as a variable.

My code is

$current_user = wp_get_current_user();
$user_id = $current_user->ID;

$loc_statuss = $wpdb->get_row( "SELECT status FROM profile_location INNER JOIN relation_user ON profile_location.loc_id=relation_user.loc_id WHERE relation_user.user_id=$user_id" );
$loc_status = $loc_statuss->status;

I have found a couple of questions the same but these answers don't seem to work for me.

Thanks

  • You are trying to get this value when, when the urser logs in ? – Cesar Henrique Damascena Aug 8 '17 at 12:44
  • @CesarHenriqueDamascena see my comment on the first answer should explain more how I am using it – Dudley Aug 8 '17 at 12:52
1

If you want current user id only then use get_current_user_id. because it reduce execution time. get_current_user_id get only current user id where wp_get_current_user get all user data. Else every things is perfect.

$user_id = get_current_user_id();

$loc_statuss = $wpdb->get_row( "SELECT status FROM profile_location INNER JOIN relation_user ON profile_location.loc_id=relation_user.loc_id WHERE relation_user.user_id=".$user_id );
$loc_status = $loc_statuss->status;
  • This returns a 0 rather than the user id. From what I have read its because I haven't loaded pluggable. Are you able to tell me how to do this or if there is another reason get_current_user_id returns zero? Thanks – Dudley Aug 8 '17 at 12:19
  • 0 is returned if no user is logged in. Which hook are you executing this code in? If any. – Jacob Peattie Aug 8 '17 at 12:35
  • If no user signed in then it returns 0. If still their is problem then use wp_get_current_user if it get id for you. Will you please tell me in which action you are writing this code or it is your custom plugin action. thanks – Rahul Parikh Aug 8 '17 at 12:35
  • @RahulParikh get_current_user_id() uses wp_get_current_user() itself, so it's not going to be any faster or behave any differently. – Jacob Peattie Aug 8 '17 at 12:36
  • yes @JacobPeattie – Rahul Parikh Aug 8 '17 at 12:41
0

Try this code:

// Set up the global variables
$user_id;
$loc_status;

// When the user login, setup all variables that you need

function get_user_informations( $redirect_to, $request, $user ) {
    //is there a user to check?
    if ( $user ) {
      $user_id = $user->id;

      $loc_statuss = $wpdb->get_row( "SELECT status FROM profile_location INNER JOIN relation_user ON profile_location.loc_id=relation_user.loc_id WHERE relation_user.user_id=".$user_id );
      $loc_status = $loc_statuss->status;

    }
}

add_filter( 'login_redirect', 'get_user_informations', 10, 3 );

More about login_redirect in the Docs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.