WordPress

[WordPress]公開側からメディアを追加する

公開側で画像をアップロードして任意の投稿のアイキャッチに設定したい場合などに。

function insert_attachment($media, $post_id, $old_id, $title, $caption) {

require_once(ABSPATH.'wp-admin/includes/image.php');
require_once(ABSPATH.'wp-admin/includes/file.php');
require_once(ABSPATH.'wp-admin/includes/media.php');
$wp_upload_dir = wp_upload_dir();
$post_data = [
'post_title' => $title,
'post_content' => $caption,
'guid' => $wp_upload_dir['url'].'/'.basename($media)
];
if ( $post_id && $thumbnail_id = media_handle_upload($media, $post_id, $post_data) ) {
if ( $old_id ) {//旧アイキャッチを削除
wp_delete_attachment($old_id, true);
}
//アイキャッチ設定
set_post_thumbnail($post_id, $thumbnail_id);
return true;
}
return false;
}

$media = 'file';
insert_attachment($media, $post_id, $old_id, $title, $caption);

$mediaはtype='file'のname

<form method="post" enctype="multipart/form-data">

<input type="file" name="file">
</form>