Associate an existing image with a post

You can modify an existing media library image using wp_insert_attachment by setting the ID key in the parameter array.

$attachment = array(
    'ID' => $existing_library_attachment_id,
    'post_parent' => $custom_post_id
);
wp_insert_attachment( $attachment );

This will update the attachment post with ID $existing_library_attachment_id to have a post_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:

  1. To make the image the “featured image” of your post, use the set_post_thumbnail function:

    set_post_thumbnail( $custom_post_id, $existing_library_attachment_id );
    
  2. 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 the get_image_tag function). If you want to add a gallery, use the shortcode.

Leave a Comment