我正在做一个插件,可以从外部API检索媒体,当我点击它(在管理上)时,它会插入一篇包含媒体、标题等的新帖子。
所以,现在,我在click上插入一篇新帖子:很好用。我是这样做的:
$title = $_POST[\'title\'];
$content = $_POST[\'content\'];
$id = $_POST[\'id\'];
$imgSrc = $_POST[\'imgSrc\'];
$my_post = array(
\'post_name\' => $id,
\'post_title\' => $title,
\'post_content\' => $content,
\'post_status\' => \'publish\',
\'post_author\' => 1,
\'post_category\' => array(8,39)
);
wp_insert_post( $my_post );
现在,这就是我被困的地方。我有一个图像URL(
$imgSrc
), 我想添加到我的帖子中。我想做的是:
将此url上载到媒体库:不知道如何将其附加到帖子:我看到了带有wp\\U insert\\U附件的内容(但我不知道如何处理)因为我对PHP很在行,我该怎么做?
最合适的回答,由SO网友:enguerranws 整理而成
对于那些知道的人:
$upload_dir = wp_upload_dir();
$image_data = file_get_contents($image_url);
$filename = basename($image_url);
if(wp_mkdir_p($upload_dir[\'path\']))
$file = $upload_dir[\'path\'] . \'/\' . $filename;
else
$file = $upload_dir[\'basedir\'] . \'/\' . $filename;
file_put_contents($file, $image_data);
$wp_filetype = wp_check_filetype($filename, null );
$attachment = array(
\'post_mime_type\' => $wp_filetype[\'type\'],
\'post_title\' => sanitize_file_name($filename),
\'post_content\' => \'\',
\'post_status\' => \'inherit\'
);
$attach_id = wp_insert_attachment( $attachment, $file, $post_ID );
require_once(ABSPATH . \'wp-admin/includes/image.php\');
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $post_ID, $attach_id );