3

I'm currently developing a WordPress theme where I want the user to be able to upload images before he register or log in to the site.

The initial problem was, you can't upload images to WordPress using the wp.media JavaScript class if you are not a registered user.

The solution I create is actually very simple:

  1. When the user arrives at the registration page, a JavaScript code checks if the user is logged in or not, if he's not we create a temporary user with a random e-mail and password and login the visitor with this newly created temporary user, all in background. After that, the idea is once the user registers with his own data, this temporary user is going to be updated with the correct visitor data.

  2. Now the tricky part. I want WordPress to identify this user as logged in without a page reload, to make this work I added a function to the action set_logged_in_cookie, so I can get the $_COOKIE data the WordPress is going to set to this new logged in user and retrieve it through the ajax call, I then set this cookie data in the local user computer with JavaScript.

Now I'm able to get the correct data for the cookie (PHP working just fine) and set it also without a problem (JavaScript looks to be working fine also). If I dump the $_COOKIE global after a page reload I get the same data I'm getting in the JavaScript code ajax call, but after I set the cookie, in the JavaScript code, without a reload and when I try to upload with the wp.media nothing works, after a page reload it works just fine.

Any sugestions? Bellow is my current code (I left only the relevant code):

 // set action to get the cookie data
 $this->setAction('set_logged_in_cookie', 'setCookieContents');
 public function setCookieContents($logged_in_cookie, $expire, $expiration, $user_id)
 {
     $this->_cookieContents = array(
         'logged_in_cookie'  =>  $logged_in_cookie,
         'expire'            =>  $expire,
         'expiration'        =>  $expiration,
         'user_id'           =>  $user_id
     );
 }

...

 public function handleAjax( $action )
 {

   header('Content-type: application/json');

   $action     =   PlulzTools::getValue('todo');

   $response = array(
       'status'    =>  'ok',
       'data'      =>  array()
   );

   switch($action)
   {
          case 'ajaxlogin' :
                 $response['data']['cookie'] = array(
                       'key'   =>  LOGGED_IN_COOKIE,
                       'data'  =>  $this->_cookieContents['logged_in_cookie']
                 );

                 echo json_encode($response);
          break;
       }

Now, in the front end JavaScript code, get the data and set the cookie (or at least, try to):

jQuery.ajax({
     url : Frontend.ajaxurl,
     type: 'POST',
     data: EnviarLogin,
     timeout: 12000
}).done(function(newresponse){

     if(newresponse.status == 'ok')
     {
          // atualizando status de login
          logged = true;

          jQuery.cookie(newresponse.data.cookie.key, newresponse.data.cookie.data);

     }
}).error(function (xhr, ajaxOptions, thrownError){

     console.log(xhr);
     console.log('Erro! Status:' + xhr.status + '; Erro thrown: ' + thrownError, + ' Description: ' + xhr.statusText);

     return false;

});
1
  • Any progress on that?
    – kaiser
    Commented Mar 16, 2014 at 1:03

2 Answers 2

1

Your problem probably starts with your callback:

public function handleAjax( $action )

To send a JSON error or success, you just have to call

wp_send_json_success( array( /* Data */ ) );
wp_send_json_error( array( /* Data */ ) );

The response will be like:

{
    success : true,
    data : [
        // Some data as key/value pairs
    ]
}

Both functions internally call wp_send_json(). This sets the appropriate header:

@header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset' ) );

and does the encoding to JSON for you:

echo json_encode( $response );

Your callback on the set Cookie filter won't work as it will never be called. Better go one level up and use wp_set_auth_cookie(). Your user registration should already allow that as one of the later registration hooks already have the user ID present: user_register or wpmu_new_user should both work for that case.

add_action( 'user_register', wpse136539userRegistration' );
function wpse136539userRegistration( $id )
{
    $user = get_user_by( 'id', $id );

    # @TODO Custom Error handling needed here
    if ( is_wp_error( $user ) )
        return;

    wp_set_current_user( $id );
    // Log the user in - set Cookie and let the browser remember it
    wp_set_auth_cookie( $id, TRUE );

    // Redirect user to his admin profile page ... @TODO maybe somewhere else
    exit( wp_safe_redirect( user_admin_url() ) );
}
1

If you're trying to make the wordpress_logged_in_HASH cookie info available to javascript to set on the client side using javascript (and thus avoiding re-rendering the page) then I think you'll have more success re-architecting to come up with another solution. The wordpress_logged_in cookie is a httponly cookie which means you don't have access to it on the client, and shouldn't expose it to javascript since this makes it vulnerable to XSS. See here for more details: http://blog.codinghorror.com/protecting-your-cookies-httponly/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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