Trying to make a plugin that can upload files directly to WP. Despite copying different blocks of code online, it seems determined to not let me upload it.
The way I'm attempting is through a XMLHttpRequest to a php file with wp_handle_upload
. I append the input file element to a formdata
and send it through the request. The data that's sent is correct and in order, as i echoed it multiple times to make sure of it, but when it gets to wp_handle_upload
, it stops working and the network tab says there was a 500 error on the request.
I've tried calling wp_handle_upload
with only the first parameter but it tells me that the form submission is invalid. I've also parsed the file data to a new variable like what's done here but to the same result.
javascript code that handles the input element file:
if ($('#active_p').is(":checked")) personDataActive = 1; //since checked isn't a boolean property, we have to analyze it to get the correct value
else personDataActive = 0;
var personDataUsers = new Array;
var personDataPlaces = new Array;
$("input[name='check_list_user[]']:checked").each(function () {
personDataUsers.push($(this).val());
})
$("input[name='check_list_places[]']:checked").each(function () {
personDataPlaces.push($(this).val());
})
//depending on the value of the id, it'll either update or insert a person
if ($('#id_p').val() > 0) id = $('#id_p').val(); //its a new person
else id = 0; //its an already existing person
let image = $('#profile_picture').prop('files');
const formData = new FormData();
formData.append("profile_picture", image[0]);
formData = new FormData();
formData.append('image', image[0]);
$.ajax({
url: "imageUpload.php",
data: formData,
processData: false,
contentType: false,
type: "POST",
success: function(response){
console.log(response);
},
error: function(response) { console.log("error: " + response)}
});
//pass all of the data as an array to make the ajax data more clean. 0 is id, 1 is name, 2 is active, 3 is birthdate, 4 is internalid, 5 is media url, 6 is users and 7 is places
personData = [id, $('#name_p').val(), personDataActive, $('#birthdate_p').val(), $('#internalid_p').val(), personDataUsers, personDataPlaces];
//ajax call to add new person!!!
$.ajax({
url: 'ajaxToPhpCalls.php', //the file to send the data to. preferably, leave it on the same folder to avoid problems
type: 'POST', //it can always be POST even if the intention is getting values, still, it's better to declare the intended type to not accidentaly overwrite stuff
data: { callFunction : "Insert", personData: personData.join(',')}, //we can't send an array directly, we have to use the .join() function to send it complete
success: function(response) {
//the response can be used for debug reasons, since it will return the same data as in Postman
//alert("Success");
console.log(response);
//hide the modal on success so there's a visual cue for the user. if it fails, they can resend the request
hideCreateModal();
var total = $("#totalNumber").val();
$("#totalNumber").val(total++); //add the new person to the total. val()++ doesn't work outside, may work inside the ()
//console.log($("#totalNumber").val());
$("body").css("cursor", "default");
resetNewPersonFields();
ResetTable();
$("body").css("cursor", "default");
},
error: function() {alert("Error"); $("body").css("cursor", "default");},
});
imageUpload.php
for WP media upload
<?php
//load both to make sure wordpress core functions are loaded
require( dirname(__FILE__) . '/../../../../../wp-config.php' );
require( dirname(__FILE__) . '/../../../../../wp-load.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
//check if request has required variable
if (! empty($_FILES["image"]))
{
$upload_overrides = array( 'test_form' => FALSE );
$movefile = wp_handle_upload( $_FILES['image'], $upload_overrides);
if ( $movefile && !isset( $movefile['error'] ) ) {
$ufiles = get_post_meta( $post_id, 'my_files', true );
if( empty( $ufiles ) ) $ufiles = array();
$ufiles[] = $movefile;
update_post_meta( $post_id, 'my_files', $ufiles );
}
exit;
}
else return "No files detected";
file input html
<div id="Imagens" class="tabcontent" style="display: none;">
<div class="form-group">
<label>Imagem</label><br>
<input type="file" id="profile_picture" name="profile_picture"><br>
<label>ou</label><br>
<a href="#" id="insertImageAnchor" class="button">Adicionar Imagem</a><br>
<img id="preview" src="https://cdn-icons-png.flaticon.com/512/983/983213.png" width=350px>
</form>
</div>
</div>
imageUpload.php
is a major security mistake. Also check your PHP error logif this then do that
but there are noelse do this
orotherwise do that
to print out messages. So e.g ifif (! empty($_FILES["profile_picture"]))
isfalse
no code is ever run to tell you that, it's just assumed it will work. PS: There are good plugins for handling local uploads of avatars and profile pics, you don't need to reinvent the wheel