How do I attach an uploaded image (attachment) to a post?

Question: I'm trying to attach (add) an already uploaded image (attachment) to a post. In wp_postmeta I added _wp_attached_file as meta_key and value = productimages/Routers/v/CISCO1941.jpg but it does not work and I cannot see the image as a post attachment! But when I use the add image button in the wordpress HTML editor, it adds the exact same field to this table, but with a different post ID!

Is there any dependency for this field? screenshot from the database:


  • Any attachment file is a post with attachment post_type. Read more here.

  • Any attachment is attached to the post via the post_parent field in the wp_posts table. In this field you need to specify the post ID to which you want to attach the attachment.

So, all you need to do is to update the field post_parent of the attachment - set the post ID in it:

wp_update_post( [
	'ID' => $attachment_id,
	'post_parent' => $post_id
] );

Or you can do it by direct query to database.

This is better because wp_update_post() does, among other things, a bunch of operations, such as creating revisions, if they are enabled, updates comment data, taxonomies. We don't need all those operations, so for code to work faster (if you're doing it for a lot of data), it's better to use a direct query:

global $wpdb;

$wpdb->update( $wpdb->posts, [ 'post_parent' => $post_id ], [ 'ID' => $attachment_id ] );

clean_post_cache( $post_id );