Jean-Paul Manuel
Jean-Paul Manuel

Reputation: 546

Wordpress - Attach uploaded image to post

I'm using the Wordpress plugin Alchimist Ajax Upload to upload an image via Ajax, the post is created after submission of the form and after uploading the unattached images. My problem is that I need to attach those uploaded images to that created post. I have the post ID and the attachment ID, is there a php method that I could write to attach those two using just their IDs? Thanks for any response I can get.

Upvotes: 0

Views: 4123

Answers (2)

Duško Angirević
Duško Angirević

Reputation: 11

If you have already uploaded attachment/media and just want to "tie" it to the existing post, just set post_parent field of the attachment/media:

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

Upvotes: 1

TeeDeJee
TeeDeJee

Reputation: 3741

Didn't try it. But maybe you could use this. Got it from the codex in combination with the get_attached_file function

// the ID of the attachment
$filename = get_attached_file( $attachment_id ); // Full path

// The ID of the post this attachment is for.
$parent_post_id = 37;

// Check the type of file. We'll use this as the 'post_mime_type'.
$filetype = wp_check_filetype( basename( $filename ), null );

// Get the path to the upload directory.
$wp_upload_dir = wp_upload_dir();

// Prepare an array of post data for the attachment.
$attachment = array(
  'guid'           => $wp_upload_dir['url'] . '/' . basename( $filename ),
  'post_mime_type' => $filetype['type'],
  'post_title'     => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
  'post_content'   => '',
  'post_status'    => 'inherit'
);

// Insert the attachment.
$attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );

// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
require_once( ABSPATH . 'wp-admin/includes/image.php' );

// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );

Upvotes: 2

Related Questions