我使用Wordpress插件Ajax上传通过Ajax上传图片,文章是在表单提交和上传后创建的。我的问题是,我需要附加那些上传的图片到创建的帖子。我有post ID和附件ID,是否有一个php方法可以使用它们的ID来附加它们?谢谢你给我的回复。
发布于 2015-05-27 10:33:15
// 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 );发布于 2022-10-08 17:00:24
如果已经上载了附件/媒体,并且只想将其“绑定”到现有的帖子,只需设置附件/媒体的post_parent字段:
wp_update_post(
array(
'ID' => $attachment_id,
'post_parent' => $post_id
)
);https://stackoverflow.com/questions/30479158
复制相似问题