我使用Wordpress插件Alchimist Ajax Upload通过Ajax上传图片,在提交表单后以及上传未附加的图片后创建帖子。我的问题是我需要将上传的图像附加到创建的帖子上。我有帖子ID和附件ID,是否有一个php方法,我可以编写,只使用他们的ID附加这两个? 感谢您的回复。
答案 0 :(得分:2)
没试过。但也许你可以用它。从codex结合get_attached_file函数
获得// 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 );