管理画面内でなく、フロントから画像をアップロードし、添付ファイルとして保存し、ついでにカスタムフィールドに書き込むという壮麗な?コードが見つかり、少しだけアレンジした。
post_idが当然必要なので、wp_insert_postなどと組み合わせる。
postへのヒモ付けが不要な場合は該当部分をキャンセルすれば良い。
//フロントから画像を普通にアップロードさせ、添付ファイルとして挿入するサンプル //準備 //frontでもメディア関係が使えるように include_once ABSPATH . 'wp-admin/includes/media.php'; include_once ABSPATH . 'wp-admin/includes/file.php'; include_once ABSPATH . 'wp-admin/includes/image.php'; //処理部分 //formの中に仕込む。formはマルチパートにすること! //$post_idを取得しておく。ただアップしたい場合は0で良いかも。 if(isset($_FILES['upload']) && !empty($_FILES['upload'])){ $upload = $_FILES['upload']; add_custom_image($post_id, $upload); } //関数 /* 画像アップロード部 最後にreturn $aidでIDを返しても良い */ function add_custom_image($post_id, $upload) { $uploads = wp_upload_dir(); /*Get path of upload dir of wordpress*/ if (is_writable($uploads['path'])) /*Check if upload dir is writable*/ { if ((!empty($upload['tmp_name']))) /*Check if uploaded image is not empty*/ { if ($upload['tmp_name']) /*Check if image has been uploaded in temp directory*/ { $file=handle_image_upload($upload); /*Call our custom function to ACTUALLY upload the image*/ $attachment = array /*Create attachment for our post*/ ( 'post_mime_type' => $file['type'], /*Type of attachment*/ 'post_parent' => $post_id, /*Post id*/ ); $aid = wp_insert_attachment($attachment, $file['file'], $post_id); /*Insert post attachment and return the attachment id*/ $a = wp_generate_attachment_metadata($aid, $file['file'] ); /*Generate metadata for new attacment*/ $prev_img = get_post_meta($post_id, 'custom_image'); /*Get previously uploaded image*/ if(is_array($prev_img)) { if($prev_img[0] != '') /*If image exists*/ { wp_delete_attachment($prev_img[0]); /*Delete previous image画像が増えていかないように*/ } } update_post_meta($post_id, 'image', $aid); /*Save the attachment id in meta data適当なフィールド名で!*/ if ( !is_wp_error($aid) ) { wp_update_attachment_metadata($aid, wp_generate_attachment_metadata($aid, $file['file'] ) ); /*If there is no error, update the metadata of the newly uploaded image*/ } } } else { echo 'Please upload the image.'; } } } function handle_image_upload($upload) { global $post; if (is_image_file( $upload['tmp_name'] )) /*Check if image*/ { /*handle the uploaded file*/ $overrides = array('test_form' => false); $file=wp_handle_upload($upload, $overrides); } return $file; } //画像がどうか調べる。wpオリジナルの関数もある function is_image_file($file_path){ //まずファイルの存在を確認し、その後画像形式を確認する if(file_exists($file_path) && exif_imagetype($file_path)){ return true; }else{ return false; } }
コメント