Joshua David Nelson

Bullshit Free WordPress Development

  • Services
  • Code
  • About
  • Contact

Programmatically Add Images to Media Library

June 3, 2015 by Joshua Nelson

Recently I built a plugin for a client that utilized a front-end Gravity Form submission to create media file entries and link them to posts. Part of the plugin was the ability to take a file uploaded to the server (in this case, by Gravity Forms) and use that url to create a media entry, so it appears within the media library. Below is the code to add an image to the media library programmatically:

<?php
/**
* Create the image attachment and return the new media upload id.
*
* @author Joshua David Nelson, [email protected]
*
* @since 03.29.2017 updated to a class, utilizing code from Takuro Hishikawa's gist linked below.
*
* @see https://gist.github.com/hissy/7352933
*
* @see http://codex.wordpress.org/Function_Reference/wp_insert_attachment#Example
*
* @link https://joshuadnelson.com/programmatically-add-images-to-media-library/
*/
class JDN_Create_Media_File {
var $post_id;
var $image_url;
var $wp_upload_url;
var $attachment_id;
/**
* Setup the class variables
*/
public function __construct( $image_url, $post_id = 0 ) {
// Setup class variables
$this->image_url = esc_url( $image_url );
$this->post_id = absint( $post_id );
$this->wp_upload_url = $this->get_wp_upload_url();
$this->attachment_id = $this->attachment_id ?: false;
return $this->create_image_id();
}
/**
* Set the upload directory
*/
private function get_wp_upload_url() {
$wp_upload_dir = wp_upload_dir();
return isset( $wp_upload_dir['url'] ) ? $wp_upload_dir['url'] : false;
}
/**
* Create the image and return the new media upload id.
*
* @see https://gist.github.com/hissy/7352933
*
* @see http://codex.wordpress.org/Function_Reference/wp_insert_attachment#Example
*/
public function create_image_id() {
if( $this->attachment_id )
return $this->attachment_id;
if( empty( $this->image_url ) || empty( $this->wp_upload_url ) )
return false;
$filename = basename( $this->image_url );
$upload_file = wp_upload_bits( $filename, null, file_get_contents( $this->image_url ) );
if ( ! $upload_file['error'] ) {
$wp_filetype = wp_check_filetype( $filename, null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_parent' => $this->post_id,
'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
'post_content' => '',
'post_status' => 'inherit'
);
$attachment_id = wp_insert_attachment( $attachment, $upload_file['file'], $this->post_id );
if( ! is_wp_error( $attachment_id ) ) {
require_once( ABSPATH . "wp-admin" . '/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $upload_file['file'] );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
$this->attachment_id = $attachment_id;
return $attachment_id;
}
}
return false;
} // end function get_image_id
}
// Example Usage
// Add an unattached image to the media library
$image_url = 'http://someimageurl';
$create_image = new JDN_Create_Media_File( $image_url );
$image_id = $create_image->attachment_id;
// Add image and attach to a post
$post_id = '3'; // the id of the post
$create_image = new JDN_Create_Media_File( $image_url, $post_id );
$image_id = $create_image->attachment_id;
view raw create-image-id.php hosted with ❤ by GitHub

I mentioned this code in a previous post, where I outlined how to link Gravity Forms with ACF Gallery fields.

Updated 3-29-17: Updated the function to a class and utilized a better method for creating the file.

Featured image via Flickr CC, by Michael D Beckwith

Filed Under: Intermediate, WordPress Tutorials Tagged With: media library

Discussion

  1. 'Mina says

    April 20, 2018 at 22:01

    Thanks for this! Just what I was looking for 🙂

  • Twitter
  • RSS Feed URL

About Me

I'm a WordPress Engineer. I build sleek, custom websites with WordPress and Genesis.

See my services and my recent work.

Contact me to get your project started.

Gravity Forms Plugin for WordPress Fastest WordPress Hosting

Recent Posts

  • Using Font Awesome Icons for WooCommerce Grid / List Toggle
  • Disable Blog: WordPress Gone Blog-less
  • Category (Taxonomy) Dropdown Filtered By Post Type
  • Weather in WordPress with Dark Sky
  • Fixing Your Deprecated Widget Constructors in WordPress 4.3
  • Twitter
  • RSS Feed URL
  • Code Snippets
  • My Plugins
  • Make a Payment

© Joshua David Nelson | Hand-Forged | WordPress + Genesis | Terms of Service | Legal | Contact