ファイルのアップロードについて詳しく知りたい人のために、主要なトピックと問題点をカバーする簡単な入門書を次に示します。これは Linux ボックス上の WordPress 3.0 を念頭に置いて書かれており、コードは概念を説明するための基本的な概要にすぎません。実装を改善するためのアドバイスを提供できる人もいると思います。基本的なアプローチの概要
画像を投稿に関連付けるには、少なくとも 3 つの方法があります。post_meta フィールドを使用して画像パスを保存するか、post_meta フィールドを使用して画像のメディア ライブラリ ID を保存するか (詳細は後述)、画像を添付ファイルとして投稿に割り当てます。この例では、post_meta フィールドを使用して、画像のメディア ライブラリ ID を保存します。YMMV。マルチパートエンコーディング
デフォルトでは、WordPress の作成および編集フォームには enctype がありません。ファイルをアップロードする場合は、"enctype='multipart/form-data'" をフォーム タグに追加する必要があります。そうしないと、$_FILES コレクションがまったくプッシュされません。WordPress 3.0 には、そのためのフックがあります。一部の以前のバージョン (詳細がわからない) では、form タグを文字列で置き換える必要があります。
function xxxx_add_edit_form_multipart_encoding()
{
echo ' enctype="multipart/form-data"';
}
add_action('post_edit_form_tag', 'xxxx_add_edit_form_multipart_encoding');
メタ ボックスとアップロード フィールドを作成する
メタ ボックスの作成方法については、ほとんどの人がすでに知っているので、ここでは詳しく説明しませんが、必要なのは、ファイル フィールドを含む単純なメタ ボックスだけであるとだけ述べておきます。以下の例では、既存の画像を探し、存在する場合はそれを表示するコードをいくつか含めました。また、post_meta フィールドを使用してエラーを渡す単純なエラー/フィードバック機能もいくつか含めました。これを WP_Error クラスを使用するように変更する必要があります...これは単なるデモンストレーション用です。
// If there is an existing image, show it
if($existing_image) {
echo '<div>Attached Image ID: ' . $existing_image . '</div>';
}
echo 'Upload an image: <input type="file" name="xxxx_image" id="xxxx_image" />';
// See if there's a status message to display (we're using this to show errors during the upload process, though we should probably be using the WP_error class)
$status_message = get_post_meta($post->ID,'_xxxx_attached_image_upload_feedback', true);
// Show an error message if there is one
if($status_message) {
echo '<div class="upload_status_message">';
echo $status_message;
echo '</div>';
}
// Put in a hidden flag. This helps differentiate between manual saves and auto-saves (in auto-saves, the file wouldn't be passed).
echo '<input type="hidden" name="xxxx_manual_save_flag" value="true" />';
}
function xxxx_setup_meta_boxes() {
// Add the box to a particular custom content type page
add_meta_box('xxxx_image_box', 'Upload Image', 'xxxx_render_image_attachment_box', 'post', 'normal', 'high');
}
add_action('admin_init','xxxx_setup_meta_boxes');
ファイルのアップロードの処理
これは大きな問題です。実際には、save_post アクションにフックしてファイルのアップロードを処理しています。コメントの多い関数を以下に含めましたが、それが使用する 2 つの主要な WordPress 関数に注意したいと思います。
wp_handle_upload() は、アップロードを処理するすべての魔法を行います。$_FILES 配列内のフィールドへの参照とオプションの配列を渡すだけです (これらについてあまり心配する必要はありません。設定する必要がある重要なものは test_form=false だけです。信じてください)。ただし、この関数は、アップロードされたファイルをメディア ライブラリに追加しません。単にアップロードを実行し、新しいファイルのパスを返します (便利なことに、完全な URL も返します)。問題がある場合は、エラーを返します。
wp_insert_attachment() は画像をメディア ライブラリに追加し、適切なサムネイルをすべて生成します。オプションの配列 (タイトル、投稿ステータスなど) と、アップロードしたばかりのファイルへのローカル パス (URL ではない) を渡すだけです。画像をメディア ライブラリに配置することの優れた点は、wp_delete_attachment を呼び出してアイテムのメディア ライブラリ ID を渡すことで、後ですべてのファイルを簡単に削除できることです (これは以下の関数で行っています)。この関数では、wp_generate_attachment_metadata() と wp_update_attachment_metadata() も使用する必要があります。これらは、メディア アイテムのメタデータを生成するという、まさに期待どおりのことを行います。
function xxxx_update_post($post_id, $post) {
// Get the post type. Since this function will run for ALL post saves (no matter what post type), we need to know this.
// It's also important to note that the save_post action can runs multiple times on every post save, so you need to check and make sure the
// post type in the passed object isn't "revision"
$post_type = $post->post_type;
// Make sure our flag is in there, otherwise it's an autosave and we should bail.
if($post_id && isset($_POST['xxxx_manual_save_flag'])) {
// Logic to handle specific post types
switch($post_type) {
// If this is a post. You can change this case to reflect your custom post slug
case 'post':
// HANDLE THE FILE UPLOAD
// If the upload field has a file in it
if(isset($_FILES['xxxx_image']) && ($_FILES['xxxx_image']['size'] > 0)) {
// Get the type of the uploaded file. This is returned as "type/extension"
$arr_file_type = wp_check_filetype(basename($_FILES['xxxx_image']['name']));
$uploaded_file_type = $arr_file_type['type'];
// Set an array containing a list of acceptable formats
$allowed_file_types = array('image/jpg','image/jpeg','image/gif','image/png');
// If the uploaded file is the right format
if(in_array($uploaded_file_type, $allowed_file_types)) {
// Options array for the wp_handle_upload function. 'test_upload' => false
$upload_overrides = array( 'test_form' => false );
// Handle the upload using WP's wp_handle_upload function. Takes the posted file and an options array
$uploaded_file = wp_handle_upload($_FILES['xxxx_image'], $upload_overrides);
// If the wp_handle_upload call returned a local path for the image
if(isset($uploaded_file['file'])) {
// The wp_insert_attachment function needs the literal system path, which was passed back from wp_handle_upload
$file_name_and_location = $uploaded_file['file'];
// Generate a title for the image that'll be used in the media library
$file_title_for_media_library = 'your title here';
// Set up options array to add this file as an attachment
$attachment = array(
'post_mime_type' => $uploaded_file_type,
'post_title' => 'Uploaded image ' . addslashes($file_title_for_media_library),
'post_content' => '',
'post_status' => 'inherit'
);
// Run the wp_insert_attachment function. This adds the file to the media library and generates the thumbnails. If you wanted to attch this image to a post, you could pass the post id as a third param and it'd magically happen.
$attach_id = wp_insert_attachment( $attachment, $file_name_and_location );
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $file_name_and_location );
wp_update_attachment_metadata($attach_id, $attach_data);
// Before we update the post meta, trash any previously uploaded image for this post.
// You might not want this behavior, depending on how you're using the uploaded images.
$existing_uploaded_image = (int) get_post_meta($post_id,'_xxxx_attached_image', true);
if(is_numeric($existing_uploaded_image)) {
wp_delete_attachment($existing_uploaded_image);
}
// Now, update the post meta to associate the new image with the post
update_post_meta($post_id,'_xxxx_attached_image',$attach_id);
// Set the feedback flag to false, since the upload was successful
$upload_feedback = false;
} else { // wp_handle_upload returned some kind of error. the return does contain error details, so you can use it here if you want.
$upload_feedback = 'There was a problem with your upload.';
update_post_meta($post_id,'_xxxx_attached_image',$attach_id);
}
} else { // wrong file type
$upload_feedback = 'Please upload only image files (jpg, gif or png).';
update_post_meta($post_id,'_xxxx_attached_image',$attach_id);
}
} else { // No file was passed
$upload_feedback = false;
}
// Update the post meta with any feedback
update_post_meta($post_id,'_xxxx_attached_image_upload_feedback',$upload_feedback);
break;
default:
} // End switch
return;
} // End if manual save flag
return;
}
add_action('save_post','xxxx_update_post',1,2);
アクセス許可、所有権、およびセキュリティ
アップロードに問題がある場合は、アクセス許可に関係している可能性があります。私はサーバー構成の専門家ではないので、この部分がおかしい場合は修正してください。
まず、wp-content/uploads フォルダーが存在し、apache:apache によって所有されていることを確認します。その場合、パーミッションを 744 に設定すると、すべてが機能するはずです。所有権は重要です。パーマを 777 に設定しても、ディレクトリが適切に所有されていないと役に立たないことがあります。
また、htaccess ファイルを使用してアップロードおよび実行されるファイルの種類を制限することも検討する必要があります。これにより、人々が画像ではないファイルをアップロードしたり、画像を装ったスクリプトを実行したりすることを防ぎます。より信頼できる情報については、おそらくこれをグーグルで検索する必要がありますが、次のように単純なファイルタイプの制限を行うことができます:
<Files ^(*.jpeg|*.jpg|*.png|*.gif)>
order deny,allow
deny from all
</Files>