Programatically add a featured image to a post (overwrite current featured image
-
I wanted to know how I could add a featured image automatically to a post after clicking update/publish post.
I wrote this code so far and it works if there is no featured image. If the post already has a featured image, I have to update the post twice to make it work.
Any clues?
Here is my code so far:
$yt_video_id is the var that gets the ID of the youtube video in the DB
add_action('save_post', 'set_WP_featured_image'); // Set post featured image from youtube video on save add_action('publish_post', 'set_WP_featured_image'); // Set post featured image from youtube video on publish // Get Youtube video image and assign it as post thumbnail function set_WP_featured_image () { $yt_video_id = get_post_meta(get_the_ID(), '_single_video_id', true); // Get jupiter field for video ID $post_thumbnail_id = get_post_thumbnail_id( get_the_ID() ); // Get the post thumbnail (if it has one) if ( ! empty( $yt_video_id ) ) { // If jupiter field not empty and post thumbnail empty $image_url = 'https://i.ytimg.com/vi/' . $yt_video_id . '/maxresdefault.jpg'; // Url to get the image $image_name = $yt_video_id . '.png'; // Set the name of the image $upload_dir = wp_upload_dir(); // Set upload folder $image_data = file_get_contents($image_url); // Get image data $unique_file_name = wp_unique_filename( $upload_dir['path'], $image_name ); // Generate unique name $filename = basename( $unique_file_name ); // Create image file name $file_path = get_site_url() . '/wp-content/uploads/' . $image_name; // Get the futur file path of the image if( !file_exists($file_path) ){ // Check if image is already in upload_dir // Check folder permission and define file location if( wp_mkdir_p( $upload_dir['path'] ) ) { $file = $upload_dir['path'] . '/' . $filename; } else { $file = $upload_dir['basedir'] . '/' . $filename; } // Create the image file on the server file_put_contents( $file, $image_data ); // Check image file type $wp_filetype = wp_check_filetype( $filename, null ); // Set attachment data $attachment = array( 'post_mime_type' => $wp_filetype['type'], 'post_title' => sanitize_file_name( $filename ), 'post_content' => '', 'post_status' => 'inherit' ); // Create the attachment $attach_id = wp_insert_attachment( $attachment, $file, $post_id ); // Include image.php require_once(ABSPATH . 'wp-admin/includes/media.php'); require_once(ABSPATH . 'wp-admin/includes/file.php'); require_once(ABSPATH . 'wp-admin/includes/image.php'); // Define attachment metadata $attach_data = wp_generate_attachment_metadata( $attach_id, $file ); // Assign metadata to attachment wp_update_attachment_metadata( $attach_id, $attach_data ); // And finally assign featured image to post set_post_thumbnail( $post_id, $attach_id ); } } }
Thanks a bunch!
- The topic ‘Programatically add a featured image to a post (overwrite current featured image’ is closed to new replies.