Use an attachment in multiple posts

I have an attachment in a post and I want to attach it to another post without detaching it from the first post, using the WP API.

Related posts

2 comments

  1. When inside of the media uploaded in the post edit screen, just search for your previously attached media and embed it in your new post.

    The relationship between posts and attachments is preserved in the database. While an attachment can only belong to one post, it can still be embedded in many posts without worry.

  2. It is not so simple to do this. In my code change post_parent field from the attachment with new post Id.

    //take all image-attachments from a post to create post for each 
        $images =& get_children( array (
                            'post_parent' => $event_id,
                            'post_type' => 'attachment',
                            'post_mime_type' => 'image'
                        ));
    
    
                if ( empty($images) ) {
                    // no attachments here
                } else { 
                    //handle each attachment
                    foreach ( $images as $attachment_id => $attachment ) {
    
                        $this->addPost( $post_id, $attachment_id, $attachment );
                    }
    ....
    
    ...
    function addPost($post_id, $attach_id, $attach)
            {
                // Create post object
    
                $new_post = array(
                'post_title'    => 'title',
                'post_status'   => 'publish',
                'post_author'   => 1,
                'post_type'     => 'post'
                );
    
                // Insert the post into the database
                // create new post that want to reattach the attatchment
    
    
                $this->unhookFromSavePost(); // see http://codex.wordpress.org/Plugin_API/Action_Reference/save_post#Avoiding_infinite_loops
                $new_post_id = wp_insert_post( $new_post ); //get post's id 
                $this->hookToSavePost();
                $attach->post_parent = $new_post_id; // post_id 
                $newAddedAttachment = wp_insert_attachment( $attach );
    

    If you want to duplicate the attachment and use it in more posts you have to follow the steps here: wp_insert_attachment.Also, it is posible to copy $attach in new object but you have to unset the ID property of this object.

    $new_attach = $attach;
    $new_attach->post_parent = $new_post_id;
    unset($new_attach[0]);     // unset first property or unset($new_attach[ID]);
    wp_insert_attachment( $new_attach);
    

Comments are closed.