I’m trying to associate an existing image from the media library with a post (It’s a custom post type), If I use wp_insert_attachment
I get a duplicate in the media library, so I’m getting the image id
and using that as the attach_id
.
$attach_id = intval( $file['id'] );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
$result = wp_update_attachment_metadata( $attach_id, $attach_data );
This doesn’t work and the $result
is false.
I’m sure I’m missing something simple. Can anybody enlighten me?
You can modify an existing media library image using
wp_insert_attachment
by setting theID
key in the parameter array.This will update the attachment post with ID
$existing_library_attachment_id
to have apost_parent
value of$custom_post_id
. However, the only thing this will affect is the permalink of the attachment post. Unless you do something else to edit your custom post itself, you won’t see any changes on that post.Here are some things you can do to attach the image to your post:
To make the image the “featured image” of your post, use the
set_post_thumbnail
function:To show the picture in the content area of your post, you need to edit the post_content of your post (with
wp_update_post
, for example). To add an individual image to your post, you can add an<img>
tag (perhaps using theget_image_tag
function). If you want to add a gallery, use the[gallery]
shortcode.I have decided to post it as a separate post and not a comment because it will be lost.
I’ve tried Ben’s solution but it modifies the attachment’s other data fields.
I ended up using this.