Skip to content

Instantly share code, notes, and snippets.

@punit5658
Created April 21, 2017 14:59
Show Gist options
  • Save punit5658/78a7905b6768bf494610db26e59f7d8c to your computer and use it in GitHub Desktop.
Save punit5658/78a7905b6768bf494610db26e59f7d8c to your computer and use it in GitHub Desktop.
How to insert media programatically from URL in WordPress?
<?php
$post_data = array('post_title' => $post_title);
$imagesrc = migrate_image($image_url, $post_id, $post_title, $post_data);
function migrate_image($image_url, $post_id, $desc, $post_data)
{
// Need to require these files
if (!function_exists('media_handle_upload')) {
require_once ABSPATH . "wp-admin" . '/includes/image.php';
require_once ABSPATH . "wp-admin" . '/includes/file.php';
require_once ABSPATH . "wp-admin" . '/includes/media.php';
}
$url = $image_url;
$tmp = download_url($url);
if (is_wp_error($tmp)) {
// download failed, handle error
@unlink($tmp);
echo "Error Image";
var_dump( $tmp->get_error_messages( ) );
}
$file_array = array();
// Set variables for storage
// fix file filename for query strings
// Here you can add other required extension like txt,pdf.
preg_match('/[^\?]+\.(jpg|jpe|jpeg|gif|png)/i', $url, $matches);
$file_array['name'] = basename($matches[0]);
$file_array['tmp_name'] = $tmp;
// If error storing temporarily, unlink
if (is_wp_error($tmp)) {
@unlink($file_array['tmp_name']);
$file_array['tmp_name'] = '';
}
// do the validation and storage stuff
$id = media_handle_sideload($file_array, $post_id, $desc, $post_data);
// If error storing permanently, unlink
if (is_wp_error($id)) {
@unlink($file_array['tmp_name']);
return $id;
}
$src = wp_get_attachment_url($id);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment