I'm doing a plugin that can retrieve media from external APIs, and when I click on it (on the admin), it insert a new post with the media, its caption, etc.

So, now, I'm inserting a new post on click : works fine. I did something like that :

$title = $_POST['title'];
$content = $_POST['content'];
$id = $_POST['id'];
$imgSrc = $_POST['imgSrc'];

$my_post = array(
  'post_name'     => $id,
  'post_title'    => $title,
  'post_content'  => $content,
  'post_status'   => 'publish',
  'post_author'   => 1,
  'post_category' => array(8,39)

wp_insert_post( $my_post );

Now, that's where I'm stuck. I have an image URL ($imgSrc), that I want to add to my post. What I want to do is :

  1. upload this url in the media library : don't know how to do that
  2. attach it to the post : I saw something with wp_insert_attachment (but I don't know how to handle it)

As I'm pretty noob to PHP, how can I do it ?


For those who would know :

$upload_dir = wp_upload_dir();
$image_data = file_get_contents($image_url);
$filename = basename($image_url);
    $file = $upload_dir['path'] . '/' . $filename;
    $file = $upload_dir['basedir'] . '/' . $filename;
file_put_contents($file, $image_data);

$wp_filetype = wp_check_filetype($filename, null );
$attachment = array(
    'post_mime_type' => $wp_filetype['type'],
    'post_title' => sanitize_file_name($filename),
    'post_content' => '',
    'post_status' => 'inherit'
$attach_id = wp_insert_attachment( $attachment, $file, $post_ID );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
wp_update_attachment_metadata( $attach_id, $attach_data );

set_post_thumbnail( $post_ID, $attach_id );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.