I use this code to upload file from the front end.
formData = new FormData;
formData.append('action', 'upload-attachment');
fileInputElement = document.getElementById('file');
formData.append('async-upload', fileInputElement.files[0]);
formData.append('name', fileInputElement.files[0].name);
formData.append('type', fileInputElement.files[0].type);
my_nonce = document.getElementById('my_nonce').value;
formData.append('_wpnonce', my_nonce);
axios.post('/wp-admin/async-upload.php', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(function(response) {
infos_contact.file_uploaded = response.data.data.filename;
infos_contact.file_uploaded_url = response.data.data.url;
})["catch"](function(error) {
console.log(error);
});
It's working fine when logged in, but not when I'm not logged. Since it's for the frontend, it's useless if it doesn't work when not logged. I guess WordPress protect the upload function if you're not logged in for security reason.
Can I use a hook to bypass this protection?
Thanks!
wp_ajax_{$action}
, then you'd need to also hook it towp_ajax_nopriv_{$action}
to have the action run for non-authenticated users.