0

I'm developing a site that is using Wordpress for database interactions, but I'm not really using features like pages or posts or widgets.

I'm trying to create an input form that allows the user to upload an image without having to go to the media library.

The image files do go to the uploads folder, but for some reason their size is 0kb and they don't work. I can't open them in a image viewer program and they don't show up in the media library.

Here is my attempt:

Ajax part:

async function sendImageToWordpress(thePath) {


    let responseForPostToDatabase = '';

    /* Ajax call here */

    let myAjax = await jQuery.ajax({

        type: "POST",
        url: adminAjaxURL, /* this adminAjaxURL variable has been defined in header.php */
        data: ({

            action: "add_attachment",
            thePath: thePath,


        }),

        success: function(response){

            responseForPostToDatabase = response;

            return('success');

        },

        error: function(){

            return('ajax error!!!!');

        }

    })

    return(responseForPostToDatabase);

    /* Return statement here */

}

Here is the relevant parts from functions.php:

//SEND IMAGE INTO WORDPRESS

function new_attachment(){

    $image_url = ($_POST["thePath"]);

    $upload_dir = wp_upload_dir();

    $image_data = file_get_contents( $image_url );

    $filename = basename( $image_url );

    if ( wp_mkdir_p( $upload_dir['path'] ) ) {
    $file = $upload_dir['path'] . '/' . $filename;
    }
    else {
    $file = $upload_dir['basedir'] . '/' . $filename;
    }

    file_put_contents( $file, $image_data );

    $wp_filetype = wp_check_filetype( $filename, null );

    echo $image_url;

    exit();
}

add_action('wp_ajax_add_attachment','new_attachment'); //add an image file

Can you point me in the right direction?

1 Answer 1

1

Ended up doing it like this:

In functions.php:

//SEND IMAGE INTO WORDPRESS

function new_attachment(){

//echo 'talking to new_attachement in functions.php';

if(

! wp_verify_nonce( $_POST['client-file-upload'], 'add_attachement' ) //adding a layer of security by verifying a nonce that was set in the addrecipe.php form field
){

    wp_nonce_ays( '' ); //Display “Are You Sure” message to confirm the action being taken. A = are Y = You S = Sure. Don't know if needed here.
}

require_once(ABSPATH . 'wp-admin/includes/admin.php');
$myfiles = $_POST["async-upload"];
$id = media_handle_upload('async-upload', 0); //post id of Client Files page
$attachment_url = wp_get_attachment_url($id);
unset($myfiles);


if ( is_wp_error($id) ) {
    $errors['upload_error'] = $id;
    $id = false;
}

if ($errors) {
    echo "<p>There was an error uploading your file.</p>";
} else {
    echo  $attachment_url;
}

exit();




}
add_action('wp_ajax_add_attachement','new_attachment'); //add an image file 

Javascript:

    jQuery('#file-form').submit(
    function (e) {
        e.preventDefault();
        let mydata = new FormData(this);
        mydata.append('action', 'add_attachement');
        jQuery.ajax({
            url: adminAjaxURL,
            type: 'POST',
            data: mydata,
            processData: false,
            contentType: false,
            success: function (result) {
                console.log(result);
                jQuery('#imageURLs').val(result);
                //$("#div1").html(str);
            }
        })
    });

PHP and HTML:

<form id="file-form" enctype="multipart/form-data">
    <p id="async-upload-wrap">
    <label for="async-upload">Lataa kuva</label>
    <input type="file" id="async-upload" name="async-upload"> <input type="submit" value="Lataa" name="html-upload">
    </p>

    <p>
    <input type="hidden" name="post_id" id="post_id" value="<?php echo '0';?>" />
    <?php wp_nonce_field('add_attachement', 'client-file-upload'); ?>
    </p>

    <p>
    <input type="submit" value="Save all changes" name="save" style="display: none;">
    </p>
    </form>

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.