1- ポストを挿入する必要がある場合は最初に
注: 投稿 ID が分かっていて、新しい ID を差し込む必要がない場合は、2 番目のステップをスキップできます。
$new_post = array(
'post_title' => $title,
'post_content' => $outputValue,
'post_category' => array($_POST['cat']), // Usable for custom taxonomies too
'tags_input' => $tags_keywords,
'post_status' => 'publish', // Choose: publish, preview, future, draft, etc.
'post_type' => 'post' //'post',page' or use a custom post type if you want to
);
//SAVE THE POST
$pid = wp_insert_post($new_post);
2- 2 番目の画像の挿入
// コード: URL から画像を挿入する場合
if(isset($_POST['the_img_link']) && $_POST['the_img_link'] != ''){
$image_url = $_POST['the_img_link'];
basename($image_url);
$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, $pid );
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( $pid, $attach_id );
}else{
// $other_attach_id is any previous added attached image
// you want it to be a default image
set_post_thumbnail( $pid, $other_attach_id )
}
// コード: 画像を挿入したい場合は PC
if ($_FILES) {
foreach ($_FILES as $file => $array) {
$attach_id = wp_insert_attachment( $attachment, $file, $pid );
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( $pid, $attach_id );
}
}else{
// $other_attach_id is any previous added attached image
// you want it to be a default image
set_post_thumbnail( $pid, $other_attach_id )
}