How to set an attachments parent post id in code?

I’ve inherited an imported wordpress site with a few issue. I have a list of attahment ids and post ids but I need to re-connect them in the code.

I’ve got a list of all attachemnt like this:

  $attachments = get_posts( array('post_type' => 'attachment','posts_per_page' => -1));

  foreach ( $attachments as $key=>$attachment ) {
  }

I’ve also got a csv of attachment ids, and which post they relate to. Now all the attahment parent post ids are ‘0’, what i need to do is update each one so it’s parnet post id is the related id in

What’s the key wordpress function in this loop set an attachemnts parnet post id? And then make sure that update is propagated to all the meta data too.

I want something like….
set_attachemnt_parent_id($attachment->ID, $myIdFromArchives);

Thanks for your help!

Edit – I have tried doing a direct update of the database id but that doesn’t work.

1 Answer
1

In WordPress – Attachments are their own post-type which means you just need to update the post using wp_update_post():

$media_post = wp_update_post( array(
    'ID'            => $attachment_id,
    'post_parent'   => $post_parent_id,
), true );

if( is_wp_error( $media_post ) ) {
    error_log( print_r( $media_post, 1 ) );
}

In the above you would pass both the Attachment ID and the Post ID which will be the attachment “parent” to the wp_update_post() function but we also want to make sure that if for whatever reason it cannot be updated – we add the WP_Error to the error_log so we can debug what went wrong.

You could also do an additional check before the wp_update_post() function to ensure the given attachment id is indeed an attachment. This is just another check so we don’t accidently update things we don’t need to:

if( 'attachment' === get_post_type( $attachment_id ) ) {
    // Update Post Code
}

Leave a Comment