WordPress: How to add images to the media library with PHP

Marc Wag­ner

Octo­ber 22, 2022

3 min read|

Word­Press offers dif­fe­rent ways to add images with PHP to the Word­Press media libra­ry. Two vari­ants I would like to intro­du­ce to you today, media_handle_sideload and wp_insert_attachment.

wp_insert_attachment #

The fol­lo­wing exam­p­le shows you how to insert images into the Word­Press media libra­ry using PHP and wp_insert_attachment.

/**
 * Adding an image to the WordPress library and creating all associated image sizes
 * 
 * @param string $path_to_file    The absolute path to the image to be added to the media library, e.g.: /wp-content/uploads/bild1.jpg
 * @param string $post_title      The title for the image
 * @param int &$attachment_id     If specified, the ID of the image will be stored in this variable after successful creation.
 * 
 * @return bool Returns true if the image was successfully created. Otherwise false is returned. 
 */
function addImageToWordPressMediaLibrary(string $path_to_file, string $post_title, &$attachment_id = null): bool{

   /**
    * Let WordPress determine the mime type of the file
    */
    $filetype = wp_check_filetype(basename($path_to_file));

    $attachment = array(
      'post_mime_type' => $filetype['type'],
      'post_title' => sanitize_title($post_title),
      'post_content' => '',
      'post_status' => 'inherit'
    );

    /**
     * Create the Post
     */
    $attachment_id = wp_insert_attachment($attachment, $path_to_file);

    if(!is_numeric($attachment_id)){
       return false;
    }

    /**
     * Create additional image sizes and store them for the image
     */
    require_once( ABSPATH . 'wp-admin/includes/image.php' );

    $attach_data = wp_generate_attachment_metadata( $attachment_id, $path_to_file );
    wp_update_attachment_metadata( $attachment_id, $attach_data );
    return true;
}

Using wp_insert_attachment the actu­al image is added to the media libra­ry. Only if this was suc­cessful, the remai­ning image for­mats are gene­ra­ted via wp_generate_attachment_metadata and then added to the image (post) via wp_update_attachment_metadata.

media_handle_sideload #

Alter­na­tively, images can also be added to the Word­Press media libra­ry with media_handle_sideload. This vari­ant is also used by the media libra­ry in the backend of your Word­Press web­site. Here you have less opti­ons, but you can save a few lines of code.

/**
 * Adding an image to the WordPress library and creating all associated image sizes
 * 
 * @param string $path_to_file    The absolute path to the image to be added to the media library, e.g.: /wp-content/uploads/bild1.jpg
 * @param string $image           The filename of the image after copying, e.g. bild1.jpg
 * @param int &$attachment_id     If specified, the ID of the image will be stored in this variable after successful creation.
 * 
 * @return bool Returns true if the image was successfully created. Otherwise false is returned. 
 */
function addImageToWordPressMediaLibrary(string $path_to_file, string $image, &$attachment_id = null): bool{
   $file_array = ["name" => $image, "tmp_name" => $path_to_file];

   // Add image to Media Library
   $attachment_id = media_handle_sideload($file_array , 0, '');

   if(!is_numeric($attachment_id )){
     return false;
   }
                
   return true;
}

Both vari­ants, if the addi­tio­nal image sizes are crea­ted, requi­re some time to add an image.

Summary #

Both media_handle_sideload and wp_insert_attachment lead to the desi­red result. The wp_insert_attachment func­tion allows to add images to the media libra­ry even wit­hout the pre­de­fi­ned image sizes of the the­me. Only by cal­ling wp_generate_attachment_metadata and saving the data by wp_update_attachment_metadata the addi­tio­nal image sizes are crea­ted. This can be espe­ci­al­ly hel­pful if seve­ral images are to be added at once. The dif­fe­rent image sizes can be added later via plug­ins like Rege­ne­ra­te­T­h­umb­nails.

88e86fcb816eff22bc917094df2862d8dd5c0e978b333e6dd5f36f808990c261 96

Arti­kel von:

Marc Wag­ner

Hi Marc here. I’m the foun­der of Forge12 Inter­ac­ti­ve and have been pas­sio­na­te about buil­ding web­sites, online stores, appli­ca­ti­ons and SaaS solu­ti­ons for busi­nesses for over 20 years. Befo­re foun­ding the com­pa­ny, I alre­a­dy work­ed in publicly lis­ted com­pa­nies and acqui­red all kinds of know­ledge. Now I want to pass this know­ledge on to my cus­to­mers.

Hast du eine Fra­ge? Hin­ter­lass bit­te einen Kom­men­tar