Image added via wp_insert_attachment is invalid?
-
Hi,
I try to use the sample code at https://developer.www.ads-software.com/reference/functions/wp_insert_attachment/ to add an image to post, and use attachment_url_to_postid to verify if the attached image is valid or not, as below.
When debugging, attachment_url_to_postid will always return 0 for the attachment added via wp_insert_attachment so the validation always fails.
I try to add an image to media library manually, then the verification will pass. So I think using wp_insert_attachment to insert media must have missed some important steps that cause the error.
<?php include "wp-load.php"; // $filename should be the path to a file in the upload directory. $filename = 'C:/wamp64/www/blogs/wp-content/uploads/2024/03/test12.jpg'; // The ID of the post this attachment is for. $parent_post_id = 76; // Check the type of file. We'll use this as the 'post_mime_type'. $filetype = wp_check_filetype( basename( $filename ), null ); // Get the path to the upload directory. $wp_upload_dir = wp_upload_dir(); // Prepare an array of post data for the attachment. $attachment = array( 'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ), 'post_mime_type' => $filetype['type'], 'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ), 'post_content' => '', 'post_status' => 'inherit' ); // Insert the attachment. $attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id ); // 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, $filename ); wp_update_attachment_metadata( $attach_id, $attach_data ); set_post_thumbnail( $parent_post_id, $attach_id ); // Verify the attached image $attach_url = wp_get_attachment_image_url($attach_id, 'full'); $attach_id2 = attachment_url_to_postid($attach_url); if ($attach_id == $attach_id2) echo "Verficiation succeeds!"; else echo "Verficiaton failed!"; ?>
- The topic ‘Image added via wp_insert_attachment is invalid?’ is closed to new replies.