Attach an image to a post with code


If you look at the media library you probably notice that all attachments are attached/unattached to a post. If the attachment is attached to a certain post, actually it’s just set as a child of that post, or its post parent is that post.

Since both attachments and posts are post and they are only two different post types, we can easily attach a attachment to a post by setting the post_parent attribute.

Here is the working codes.

function plol_image_attach_to_post( $post_id = '', $image_id = '' ) {
    global $wpdb;
    $post_id = (string)$post_id; // Parent post ID
    $image_id = (string)$image_id; // attachment ID
    $result = $wpdb->update( $wpdb->posts, array('post_parent'=>$post_id), array('ID'=>$image_id) );
    if ( $result === FALSE ) {
        return false;
    } else {
        return true;

In my previous post on how to upload an image from front-end, the image is only inserted to the media library not attached to any post. You can implement above code to get it attached.



Author: Leo

My name is Leo who’s behind this blog. I’ve been working with wordpress since 2010. I’ll write about themes, plugins, tutorials and all about wordpress here. Hope you find it useful!

Leave a Reply

Your email address will not be published. Required fields are marked *