Skip to content

Instantly share code, notes, and snippets.

@elipettingale
Last active April 1, 2020 07:52
Show Gist options
  • Select an option

  • Save elipettingale/71bd035a90f6881323866fa1794a9039 to your computer and use it in GitHub Desktop.

Select an option

Save elipettingale/71bd035a90f6881323866fa1794a9039 to your computer and use it in GitHub Desktop.
Wordpress | Upload post featured image from url
<?php
$upload = wp_upload_bits(basename($image_url), null, file_get_contents($image_url));
$image_file = $upload['file'];
$image_type = wp_check_filetype($image_file, null);
$attachment_id = wp_insert_attachment([
'post_mime_type' => $image_type['type'],
'post_title' => sanitize_file_name($image_file),
'post_content' => '',
'post_status' => 'inherit'
], $image_file, $post_id);
wp_update_attachment_metadata($attachment_id, wp_generate_attachment_metadata($attachment_id, $image_file));
set_post_thumbnail($post_id, $attachment_id);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment