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:
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.
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;
});