Title: Set featured image with javascript
Last modified: September 15, 2019

---

# Set featured image with javascript

 *  [Invizion](https://wordpress.org/support/users/invizion/)
 * (@invizion)
 * [6 years, 8 months ago](https://wordpress.org/support/topic/set-featured-image-with-javascript/)
 * Hello,
 * I need your help to acomplish one task. I’m sure I’m missing something but can’t
   figure out what.
 * I have an ajax call that send’s an URL (image file) and a file name to PHP to
   upload it to media gallery. After the upload, it returns the image ID and then
   I need to insert it into post. This last step is where I need your help. I already
   confirmed data sent back to ajax call is the ID of the image (open the image 
   in gallery and ID is the same sent to Ajax call).
 * My PHP function:
 *     ```
       function file_upload_auto ()
       {
           if (!isset ($_REQUEST['file_up'])) {
   
               $return_value = 'Something went wrong' ;
               return $return_value ;
           }
   
           $file = $_REQUEST['file_up'];
           $filename = $_REQUEST['fname'];
   
   
           // Add Featured Image to Post
           $image_url        = $file; // Define the image URL here
           $image_name       = $filename . ".jpg";
           $upload_dir       = wp_upload_dir(); // Set upload folder
           $image_data       = file_get_contents($image_url); // Get image data
           $unique_file_name = wp_unique_filename( $upload_dir['path'], $image_name ); // Generate unique name
           $filename         = basename( $unique_file_name ); // Create image file name
   
           // Check folder permission and define file location
           if( wp_mkdir_p( $upload_dir['path'] ) ) {
               $file = $upload_dir['path'] . '/' . $filename;
           } else {
               $file = $upload_dir['basedir'] . '/' . $filename;
           }
   
           // Create the image  file on the server
           file_put_contents( $file, $image_data );
   
           // Check image file type
           $wp_filetype = wp_check_filetype( $filename, null );
   
           // Set attachment data
           $attachment = array(
               'post_mime_type' => $wp_filetype['type'],
               'post_title'     => sanitize_file_name( $filename ),
               'post_content'   => '',        
               'post_status'    => 'inherit'
           );
   
           // Create the attachment
           $attach_id = wp_insert_attachment( $attachment, $file, $post_id );
   
           // Include image.php
           require_once(ABSPATH . 'wp-admin/includes/image.php');
   
           // Define attachment metadata
           $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
   
           // Assign metadata to attachment
           wp_update_attachment_metadata( $attach_id, $attach_data );
   
           //$duvida = json_encode($attach_id);
   
           echo $attach_id;
           wp_die();
   
       }
       ```
   
 * My JS:
 *     ```
       function fileuploader(file, filename){
           console.log(file);
           console.log(filename);
           $.ajax({
               type: 'POST',
               dataType: 'json',
               url: '/wp-admin/admin-ajax.php',
               data: {
                   action: 'call_file_uploader',
                   file_up: file,
                   fname: filename
               },
   
               success: function(data) {
                   console.log(data);
                   wp.media.featuredImage.set( data );
               },
               error: function (jqXHR, exception) {
               var msg = '';
               if (jqXHR.status === 0) {
                   msg = 'Not connect.\n Verify Network.';
               } else if (jqXHR.status == 404) {
                   msg = 'Requested page not found. [404]';
               } else if (jqXHR.status == 500) {
                   msg = 'Internal Server Error [500].';
               } else if (exception === 'parsererror') {
                   msg = 'Requested JSON parse failed.';
               } else if (exception === 'timeout') {
                   msg = 'Time out error.';
               } else if (exception === 'abort') {
                   msg = 'Ajax request aborted.';
               } else {
                   msg = 'Uncaught Error.\n' + jqXHR.responseText;
               }
   
           }, 
           });    
       }
       ```
   
 * I thought when using:
    `wp.media.featuredImage.set( data );` it was supposed 
   to attach the image to the post, but it seems nothing happens. If I open the 
   gallery inside the new post page, the image is right there to be used.
 * Could someone point me in the right direction please?

Viewing 1 replies (of 1 total)

 *  [mrtom414](https://wordpress.org/support/users/mrtom414/)
 * (@mrtom414)
 * [6 years, 8 months ago](https://wordpress.org/support/topic/set-featured-image-with-javascript/#post-11965685)
 * Are you using the REST API ? The REST API is what wordpress uses to make the 
   front end respond to ajax request. Good luck

Viewing 1 replies (of 1 total)

The topic ‘Set featured image with javascript’ is closed to new replies.

## Tags

 * [ajax](https://wordpress.org/support/topic-tag/ajax/)
 * [featured image](https://wordpress.org/support/topic-tag/featured-image/)
 * [featuredimage](https://wordpress.org/support/topic-tag/featuredimage/)

 * In: [Developing with WordPress](https://wordpress.org/support/forum/wp-advanced/)
 * 1 reply
 * 2 participants
 * Last reply from: [mrtom414](https://wordpress.org/support/users/mrtom414/)
 * Last activity: [6 years, 8 months ago](https://wordpress.org/support/topic/set-featured-image-with-javascript/#post-11965685)
 * Status: not resolved

## Topics

### Topics with no replies

### Non-support topics

### Resolved topics

### Unresolved topics

### All topics
