I have AJAX image upload function where I can get attachment_id value. I want to save that as global variable and use it in different function that sets post thumbnail when it's exist.

This is what I have so far and NOT working.

Image upload

function write_here_featured_image_upload() {

    // Temporary post id
    $post_id = 0;

    // 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' );

    // Let WordPress handle the upload.
    global $attachment_id;
    $attachment_id = media_handle_upload('file' , $post_id );
    $image_attributes = wp_get_attachment_image_src( $attachment_id, 'thumbnail' );

    echo $image_attributes[0];

add_action( 'wp_ajax_write_here_img_upload', 'write_here_featured_image_upload' );

Add post function

function write_here_add_new_post() {
    $post_id = wp_insert_post($new_post);
    //echo "Post Added ".$post_id;

        set_post_thumbnail( $post_id, $attachment_id );

global $attachment_id does not seem to be working. what is the proper way to do this?

  • It is not clear what you are doing. When does the AJAX request run? You realize that an AJAX request is an independent request to the server and globals won't populate across requests?
    – s_ha_dum
    Commented Nov 24, 2015 at 23:56
  • Thank you for the comment! I want to upload an image with AJAX and get attachment_id then use that attachment_id when the entire form is submitted to set the post thumbnail.
    – Ohsik
    Commented Nov 24, 2015 at 23:59

1 Answer 1


Taking into account your comments to your question, what you should do is:

  • Your AJAX function should return the attachment ID to the client
  • The frontend script should catch that response and store the attachment ID somewhere, or just populate a hidden input field in your form
  • When you submit the entire form - add the attachment ID to the POST. If you have populated a hidden input field - the attachment ID will be automatically added to POST.

Don't forget to do some security checks when submitting the form - is the current user an author of the post with 'attachment ID' ID?

  • Yes I figured I can set hidden field value to attachment_id which I can use to submit a form. I'm not sure about the security check tho. I'm send wp_nonce_field( 'new-post', 'new-post-nonce' ) on form submit and check that on the function. Will this be good enough?
    – Ohsik
    Commented Nov 25, 2015 at 4:07

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.