Programmatically Adding Images To Media Library Using Ajax And JQuery

We can  here very  easily upload or add image into the media library  using ajax and jquery,
WordPress so many functions for upload media library.

but we use effortless and smooth ways.
We need to implement the following step.

Step 1:
Create a form using a template or shortcode and etc.
Here we use WordPress shortcode

<?php
function add_media_function(){
?>
<div class="uploaded_image">
  <img src="" id="uploaded_image">
</div>
<input type="file" name="profile_image" id="profile_image" size="40" class="wpcf7-form-control wpcf7-file" accept=".gif,.png,.jpg,.jpeg,.mp4,.mpg,.wav,.wmv" aria-invalid="false">
<input type="submit" id="submit" value="Upload" name="submit">
<?php 
}?>

<?php
add_shortcode( 'cutom_image_load', 'add_media_function' );

Step 2:
Now we need to  Enqueue Scripts  
Create custom.js and enqueue the JQuery library file into function.php.

/*enqueue script*/
function custom_enqueue(){
    wp_enqueue_script('jquery-library-file','https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js');
  
  wp_enqueue_script('custom-js',get_template_directory_uri() . '/assets/js/custom.js');
  wp_localize_script( 'custom-js', 'custom_ajax_object',
    array( 
      'ajaxurl' => admin_url( 'admin-ajax.php' )
    )
  );
}


add_action( 'wp_enqueue_scripts', 'custom_enqueue' );
/*End*/

Step 3:

Now implement the following code into custom.js
on click event call fiu_upload_file action passing form data.

jQuery(document).ready(function($) {
    jQuery('#submit').bind( 'click', function (e){
    var fd = new FormData();
    var file = jQuery("#profile_image");
    var caption = jQuery(this).find('input[name=profile_image]');
    var individual_file = jQuery('#profile_image')[0].files[0];
    fd.append("file", individual_file);
    var individual_capt = caption.val();
    fd.append("caption", individual_capt);  
    fd.append('action', 'fiu_upload_file');  
    jQuery.ajax({
    type: 'POST',
    url: custom_ajax_object.ajaxurl,
    data: fd,
    contentType: false,
    processData: false,
    success: function(uploaded_image){
               jQuery('#uploaded_image').attr('src',uploaded_image);
        }
    });
 });
});

Step 4:
Create custom action for uploading an image into media library into function.php.

Here we get passing data or image,upload the image into the upload folder also insert into the post table 

/ file upload process
function fiu_upload_file(){

  // WordPress environmet
  require( dirname(__FILE__) . '/../../../wp-load.php' );
  
  // it allows us to use wp_handle_upload() function
  require_once( ABSPATH . 'wp-admin/includes/file.php' );
  
  // you can add some kind of validation here
  if( empty( $_FILES[ 'file' ] ) ) {
    wp_die( 'No files selected.' );
  }
  
  $upload = wp_handle_upload( 
    $_FILES[ 'file' ], 
    array( 'test_form' => false ) 
  );
  
  if( ! empty( $upload[ 'error' ] ) ) {
    wp_die( $upload[ 'error' ] );
  }
  
  // it is time to add our uploaded image into WordPress media library
  $attachment_id = wp_insert_attachment(
    array(
      'guid'           => $upload[ 'url' ],
      'post_mime_type' => $upload[ 'type' ],
      'post_title'     => basename( $upload[ 'file' ] ),
      'post_content'   => '',
      'post_status'    => 'inherit',
    ),
    $upload[ 'file' ]
  );
  
  if( is_wp_error( $attachment_id ) || ! $attachment_id ) {
    wp_die( 'Upload error.' );
  }
  
  // update medatata, regenerate image sizes
  require_once( ABSPATH . 'wp-admin/includes/image.php' );
  
  wp_update_attachment_metadata(
    $attachment_id,
    wp_generate_attachment_metadata( $attachment_id, $upload[ 'file' ] )
  );
  
  $image_data = wp_get_attachment_url($attachment_id);
  echo $image_data;

  exit;
}

add_action('wp_ajax_fiu_upload_file', 'fiu_upload_file');

Note: image upload into wp-content\uploads/current_year/current_month.

           Example: C:\xampp\htdocs\the-code-hub\wp-content\uploads\2023\01/investor-banner.jpg
           Image Path: http://localhost/the-code-hub/wp-content/uploads/2023/01/investor-banner.jpg

Please review the video :

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories