2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2019-02-14

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

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>
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?