首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Wordpress -将上传的图像附加到post

问Wordpress -将上传的图像附加到post
EN

Stack Overflow用户
提问于 2015-05-27 09:59:55
回答 2查看 3.7K关注 0票数 0

我使用Wordpress插件Ajax上传通过Ajax上传图片,文章是在表单提交和上传后创建的。我的问题是,我需要附加那些上传的图片到创建的帖子。我有post ID和附件ID,是否有一个php方法可以使用它们的ID来附加它们?谢谢你给我的回复。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-05-27 10:33:15

没试过。但也许你可以用这个。它是从法典和文件函数结合而来的

代码语言:javascript
复制
// 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 );
票数 2
EN

Stack Overflow用户

发布于 2022-10-08 17:00:24

如果已经上载了附件/媒体,并且只想将其“绑定”到现有的帖子,只需设置附件/媒体的post_parent字段:

代码语言:javascript
复制
wp_update_post(
    array(
        'ID' => $attachment_id,
        'post_parent' => $post_id
    )
);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30479158

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档