Associate an existing image with a post

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.

Read More

I’m sure I’m missing something simple. Can anybody enlighten me?

Related posts

2 comments

  1. 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 [gallery] shortcode.

  2. 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.

                $attachment = array(
                    'ID' => $att_id,
                    'post_parent' => $custom_post_id,
                );
    
                $res = wp_update_post($attachment);
    

Comments are closed.