Skip to content

Instantly share code, notes, and snippets.

@gkarthikeyanmca
Last active October 18, 2023 13:57
Show Gist options
  • Save gkarthikeyanmca/35cd2481e63de7b8e00cb185d61d01e5 to your computer and use it in GitHub Desktop.
Save gkarthikeyanmca/35cd2481e63de7b8e00cb185d61d01e5 to your computer and use it in GitHub Desktop.
<?php
/*
Function to import image from URL to WordPress media library and assign to a post
@params
$post_id - The post ID for which you need to assign the uploaded image as featured image
$image_url - The external image URL which needs to be imported to WordPress media library
*/
function import_featured_image_from_url( $post_id = '', $image_url ='' ) {
//Check both post_id and image_url is not empty
if($post_id == '' || $image_url == '') {
return;
}
//Get the post title of the post_id
$title = get_post_field( 'post_title', $post_id );
//Handle Upload - Refer https://developer.wordpress.org/reference/functions/media_sideload_image/
$attach_id = media_sideload_image($image_url, $post_id, null, 'id');
//require_once(ABSPATH . 'wp-admin/includes/media.php'); //Include this if you are importing from root or outside of wp-content folder
//require_once(ABSPATH . 'wp-admin/includes/file.php'); //Include this if you are importing from root or outside of wp-content folder
// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata( $attach_id, get_attached_file( $attach_id ) );
wp_update_attachment_metadata( $attach_id, $attach_data );
//set ALT text
update_post_meta($attach_id, '_wp_attachment_image_alt', $title);
//Set default image title with post title
$args=array(
'ID' => $attach_id,
'post_title' => $title
);
wp_update_post($args);
//assign uploaded image as featured image for the post_id
set_post_thumbnail( $post_id, $attach_id );
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment