Get uploaded image and attach it to the new post

by Marcelo Henriques Cortez   Last Updated January 18, 2018 13:08 PM

What I'm doing:

Publishing a post that has some of it's fields checked via AJAX.

The problem:

The images posted are not being saved. All the rest of the infos are. The image is not uploaded to the server.

What I tried:

I tried using $_POST, and it was working like that, before I had to check stuff with AJAX, and had to use .preventDefault() and .submit(). Since I had to use AJAX, tried a bunch of stuff, including the fileReader().

What's being done in the code:

When the user clicks on the 'submit', I get the fields that have to be checked via JS, pass them with AJAX to PHP, if everything is ok, I return them to the JS and activate the .submit() with the form ID.

The part of the code that has the 'input=file':

<input class="text-input file-input img_destaque" name="img_destaque" type="file" id="img_destaque" multiple="false" />

The part of the code that has the submit button:

<input type="submit" class="btn-pub-ad cadastro-anuncio" id="publicar" name="publicar" value="PUBLICAR">

The part of the code that handles the info and sends via AJAX:

var img_destaque = $('#img_destaque').val();
type: "POST",
url: clocal.ajaxurl,
dataType: "html",
data: {
    'img_destaque': img_destaque,
success: function (data) {
    $data = $(data);
    if ($('.linha-sucesso').length){

The part of the code that gets what was sent via AJAX and includes the PHP that has the code to create the post:

function publish_anuncio() {
    $data = esc_sql( $_POST );
    if (!is_wp_error($errors)) :
        $errors = new WP_Error;
    if ( $data['btn_clicked'] === 'publicar' ) :
        include 'inc/inserir-anuncios-verificacao.php';

The part where the file should be handled, stored and attached to the post:

$postID = wp_insert_post($new_post);
//treating the images
// These files need to be included as dependencies when on the front end.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );

if (in_array( 'loja', (array) $current_user->roles )):
// Let WordPress handle the upload.
$img_id01 = media_handle_upload( $data['img_destaque'], $postID );
update_post_meta($postID, 'img_id01', $img_id01);

Answers 1

You have to use the javascript FormData object to upload files via ajax. A simple tutorial is provided here. In PHP the file will be available via the globals $_FILES and $_POST.

January 18, 2018 13:03 PM

Related Questions

wp_handle_upload returns empty error array

Updated May 30, 2015 23:03 PM

Media Library Image Upload Issues

Updated August 16, 2018 08:08 AM