问题描述

我在 WordPress 管理员的”Pages” 中添加了一个新页面,并添加了几个自定义字段。我也希望能够将一个上传图像字段添加到页面编辑器 – 有没有办法通过 custom-fields?

或者如果我需要这个能力,还有不同的方向吗?

最佳解决方案

对于任何想要了解更多文件上传的人来说,这里是一个简要的介绍主要话题和痛点的介绍。这是在 Linux 盒子上写的 WordPress 3.0,代码只是教授概念的基本概述。我相信这里的一些人可以提供改进实施的建议。

概述您的基本方法

将图像与帖子相关联至少有三种方法:使用 post_meta 字段存储图像路径,使用 post_meta 字段来存储图像的媒体库 ID(稍后再更新),或将图像分配给帖子作为附件。此示例将使用 post_meta 字段来存储图像的媒体库 ID 。 YMMV 。

多部分编码

默认情况下,WordPress 创建& 编辑表单没有 enctype 。如果要上传文件,则需要将”enctype=’multipart/form-data'” 添加到表单标签中,否则 $ _FILES 集合将不会被推送。在 WordPress 3.0 中,有一个钩子。在某些以前的版本 (不确定具体细节) 中,您必须将字符串替换为表单标签。

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 类… 它只是为了演示。

function xxxx_render_image_attachment_box($post) {

    // See if there's an existing image. (We're associating images with posts by saving the image's 'attachment id' as a post meta value)
    // Incidentally, this is also how you'd find any uploaded files for display on the frontend.
    $existing_image_id = get_post_meta($post->ID,'_xxxx_attached_image', true);
    if(is_numeric($existing_image_id)) {

        echo '<div>';
            $arr_existing_image = wp_get_attachment_image_src($existing_image_id, 'large');
            $existing_image_url = $arr_existing_image[0];
            echo '<img src="'%20.%20$existing_image_url%20.%20'" />';
        echo '</div>';

    }

    // If there is an existing image, show it
    if($existing_image_id) {

        echo '<div>Attached Image ID: ' . $existing_image_id . '</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 操作来实际处理文件上传。我已经在下面添加了一个 heavily-commented 功能,但是我想注意它使用的两个关键的 WordPress 功能:

wp_handle_upload() 执行所有的魔术,好的,处理上传。你只需要在 $ _FILES 数组中传递一个对你的字段的引用,并且选择一个数组 (不要太担心这些 – 你需要设置的唯一重要的一个是 test_form = false 。但是,此功能不会将上传的文件添加到媒体库。它只是上传并返回新文件的路径 (并且,并且,方便地,完整的 URL) 。如果有问题,它会返回一个错误。

wp_insert_attachment() 将图像添加到媒体库,并生成所有适当的缩略图。您只需传递一系列选项 (标题,帖子状态等) 和 LOCAL 路径 (而不是 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 文件限制上传和执行的文件类型。这可以防止人们上传不是图像的文件,也不会执行伪装成图像的脚本。你应该可以 google 这个更权威的信息,但你可以这样做简单的文件类型限制:

<Files ^(*.jpeg|*.jpg|*.png|*.gif)>
order deny,allow
deny from all
</Files>

参考文献

注:本文内容整合自 Google/Baidu/Bing 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛。