Last active
June 28, 2019 07:34
-
-
Save johnalarcon/7149118448cef9eb73c0da71befa8124 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| // Loose method | |
| public function insert_featured_image($plugin_id, $image_path) { | |
| // Get the filename from the target. | |
| $filename = basename($image_path); | |
| // Get thumbnail id, if any. | |
| $thumbnail_id = get_post_thumbnail_id($plugin_id); | |
| // Delete existing image(s). | |
| if (!empty($thumbnail_id)) { | |
| $metadata = wp_get_attachment_metadata($thumbnail_id); | |
| wp_delete_attachment($thumbnail_id, true); | |
| $files_del = wp_delete_attachment_files($plugin_id, $metadata, false, $image_path); | |
| } | |
| // Copy the file into the content directory structure. | |
| $filesave = wp_upload_bits($filename, null, file_get_contents($image_path)); | |
| // If error copying image over, bail. | |
| if (!empty($filesave['error'])) { | |
| return false; | |
| } | |
| // Setup properties to insert image as an attachment. | |
| $attachment = array( | |
| 'post_mime_type' => 'image/jpeg', | |
| 'post_parent' => 0, | |
| 'post_title' => preg_replace('/\.[^.]+$/', '', $filename), | |
| 'post_content' => '', | |
| 'post_status' => 'inherit' | |
| ); | |
| $attachment_id = wp_insert_attachment($attachment, $filesave['file'], $thumbnail_id); | |
| // Error inserting attachment record? Bail. | |
| if (is_wp_error($attachment_id)) { | |
| return false; | |
| } | |
| // Ensure needed functions are present. | |
| require_once(PATH_ADMIN.'/includes/image.php'); | |
| // Generate metadata for the attachment. | |
| $metadata = wp_generate_attachment_metadata($attachment_id, $filesave['file']); | |
| // Update attachment metadata. | |
| wp_update_attachment_metadata($attachment_id, $metadata); | |
| // | |
| set_post_thumbnail($plugin_id, $attachment_id); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment