1

I have a custom page where I ask users to log in to access the page. Once they log in, I would like to redirect them to the same page but I want to add on their user ID to the URL string in the redirect. This is just for analytics, the actual content is being protected by if (current_user_can('')){}

Here's the code I have tried in my password protected page:

<?php
    $userID = get_current_user_id();

    $args = array(
        'echo'           => true,
        'remember'       => true,
        'redirect'       => ( is_ssl() ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . '?uid=' . $userID,
        'form_id'        => 'loginform',
        'id_username'    => 'user_login',
        'id_password'    => 'user_pass',
        'id_remember'    => 'rememberme',
        'id_submit'      => 'wp-submit',
        'label_username' => __( 'Username or Email Address' ),
        'label_password' => __( 'Password' ),
        'label_remember' => __( 'Remember Me' ),
        'label_log_in'   => __( 'Log In' ),
        'value_username' => '',
        'value_remember' => false
    );
    wp_login_form($args);

?>

Obviously this won't work(returns "0") since it's trying to get the user's ID before they're logged in, but I can't think of how I would go about this.

  • If the user is connected, you don't need to pass the user identifier as a page parameter (and it can be modified by the user then it makes a security problem), you just have to use these functions : developer.wordpress.org/reference/functions/is_user_logged_in codex.wordpress.org/Function_Reference/wp_get_current_user – mmm Feb 1 '18 at 18:08
  • @mmm thank you for the response, I am not using the URL parameter as a security measure, just an analytics measure. I am displaying the protected content using if (current_user_can('')){} They just want to be able to see the User ID in the page analytics, so I'm trying to pass the User ID into the URL on redirect. – user13286 Feb 1 '18 at 18:16
2

you can add the user identifier à the redirection URL with this filter

add_filter("login_redirect", function ($redirect_to, $requested_redirect_to, $user) {

    $redirect_to = add_query_arg([
        "user_id" => $user->ID,
    ], $redirect_to);


    return $redirect_to;

}, 10, 3);
| improve this answer | |
0

I was able to resolve this by separating the login page from the page with the content. So I have one page that has the login form and at the top it checks if the user is logged in, if they are, it redirects them to the protected content page with their User ID in the URL, otherwise it displays the login form.

| improve this answer | |

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.