如何使用WordPress metabox进行多个图像上传?

如何使用WordPress metabox进行多个图像上传?,wordpress,image-upload,meta-boxes,Wordpress,Image Upload,Meta Boxes,您好我用WordPress Meta box创建了一个图像上传,但它只适用于JPG扩展 根据这一准则 function add_custom_meta_boxes() { // Define the custom attachment for posts add_meta_box( 'wp_custom_attachment', 'Product Images', 'wp_custom_attachment', '

您好我用WordPress Meta box创建了一个图像上传,但它只适用于JPG扩展

根据这一准则

function add_custom_meta_boxes() {

    // Define the custom attachment for posts
    add_meta_box(
        'wp_custom_attachment',
        'Product Images',
        'wp_custom_attachment',
        'post',
        'normal'
    );


} // end add_custom_meta_boxes
add_action('add_meta_boxes', 'add_custom_meta_boxes');

function wp_custom_attachment() {

    wp_nonce_field(plugin_basename(__FILE__), 'wp_custom_attachment_nonce');

    $html = '<p class="description">';
        $html .= 'Upload your Image here.';
    $html .= '</p>';
    $html .= '<input type="file" id="wp_custom_attachment" name="wp_custom_attachment" value="" size="25" />';

    echo $html;

} // end wp_custom_attachment

function save_custom_meta_data($id) {

    /* --- security verification --- */
    if(!wp_verify_nonce($_POST['wp_custom_attachment_nonce'], plugin_basename(__FILE__))) {
      return $id;
    } // end if

    if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
      return $id;
    } // end if

    if('page' == $_POST['post_type']) {
      if(!current_user_can('edit_page', $id)) {
        return $id;
      } // end if
    } else {
        if(!current_user_can('edit_page', $id)) {
            return $id;
        } // end if
    } // end if
    /* - end security verification - */

    // Make sure the file array isn't empty
    if(!empty($_FILES['wp_custom_attachment']['name'])) {

        // Setup the array of supported file types. In this case, it's just JPG.
        $supported_types = array('image/jpg', 'image/jpeg', 'image/pjpeg');

        // Get the file type of the upload
        $arr_file_type = wp_check_filetype(basename($_FILES['wp_custom_attachment']['name']));
        $uploaded_type = $arr_file_type['type'];

        // Check if the type is supported. If not, throw an error.
        if(in_array($uploaded_type, $supported_types)) {

            // Use the WordPress API to upload the file
            $upload = wp_upload_bits($_FILES['wp_custom_attachment']['name'], null, file_get_contents($_FILES['wp_custom_attachment']['tmp_name']));

            if(isset($upload['error']) && $upload['error'] != 0) {
                wp_die('There was an error uploading your file. The error is: ' . $upload['error']);
            } else {
                add_post_meta($id, 'wp_custom_attachment', $upload);
                update_post_meta($id, 'wp_custom_attachment', $upload);
            } // end if/else

        } else {
            wp_die("The file type that you've uploaded is not a JPG.");
        } // end if/else

    } // end if

} // end save_custom_meta_data
add_action('save_post', 'save_custom_meta_data');

function update_edit_form() {
    echo ' enctype="multipart/form-data"';
} // end update_edit_form
add_action('post_edit_form_tag', 'update_edit_form');
而且它工作得很好

我现在的问题是如何创建多个图像上传,并为其提供更多受支持的类型


谢谢

有一个快速而好的方法/实践来实现这一点


有一种快速且良好的方法/实践可以实现这一点


我在站点中找到了该代码,并对其进行了一些修改

//***************************** Start banner images metabox in page page ***********************



function call_Multi_Image_Uploader()
{
    new Multi_Image_Uploader();
}
function get_images($post_id=null)
{
    global $post;

    if ($post_id == null)
    {
        $post_id = $post->ID;
    }

    $value = get_post_meta($post_id, 'images', true);
    $images = unserialize($value);
    $result = array();
    if (!empty($images))
    {
        foreach ($images as $image)
        {
            $image = str_replace('.jpg', '-1903x428.jpg' , $image);
            $result[] = $image;
        }
    }
    return $result;
}

if (is_admin())
{
    add_action('load-post.php', 'call_Multi_Image_Uploader');
    add_action('load-post-new.php', 'call_Multi_Image_Uploader');
}
/**
 * Multi_Image_Uploader
 */
class Multi_Image_Uploader
{
    var $post_types = array();

    /**
     * Initialize Multi_Image_Uploader
     */
    public function __construct()
    {
        $this->post_types = array('page');     //limit meta box to certain post types
        add_action('add_meta_boxes', array($this, 'add_meta_box'));
        add_action('save_post', array($this, 'save'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'));
    }

    /**
     * Adds the meta box container.
     */
    public function add_meta_box($post_type)
    {
        if (in_array($post_type, $this->post_types))
        {
            add_meta_box(
                    'multi_image_upload_meta_box'
                    , __('Banner Image Upload', 'textdomain')
                    , array($this, 'render_meta_box_content')
                    , $post_type
                    , 'advanced'
                    , 'high'
            );
        }
    }
    /**
     * Save the images when the post is saved.
     *
     * @param int $post_id The ID of the post being saved.
     */
    public function save($post_id)
    {    /*
         * We need to verify this came from the our screen and with proper authorization,
         * because save_post can be triggered at other times.
         */

        // Check if our nonce is set.
        if (!isset($_POST['inner_custom_box_nonce']))
            return $post_id;

        $nonce = $_POST['inner_custom_box_nonce'];

        // Verify that the nonce is valid.
        if (!wp_verify_nonce($nonce, 'inner_custom_box'))
            return $post_id;

        // If this is an autosave, our form has not been submitted,
        //     so we don't want to do anything.
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
            return $post_id;

        // Check the user's permissions.
        if ('page' == $_POST['post_type'])
        {
            if (!current_user_can('edit_page', $post_id))
                return $post_id;
        } else
        {
            if (!current_user_can('edit_post', $post_id))
                return $post_id;
        }

        /* OK, its safe for us to save the data now. */
        // Validate user input.
        $posted_images = $_POST['images'];
        $images = array();
        if (!empty($posted_images))
        {
            foreach ($posted_images as $image_url)
            {
                if (!empty($image_url))
                    $images[] = esc_url_raw($image_url);
            }
        }

        // Update the images meta field.
        update_post_meta($post_id, 'images', serialize($images));
    }

    /**
     * Render Meta Box content.
     *
     * @param WP_Post $post The post object.
     */
    public function render_meta_box_content($post)
    {

        // Add an nonce field so we can check for it later.
        wp_nonce_field('inner_custom_box', 'inner_custom_box_nonce');

        // Use get_post_meta to retrieve an existing value from the database.
        $value = get_post_meta($post->ID, 'images', true);

        $metabox_content = '<div id="images"></div><input type="button" onClick="addRow()" value="Add Image" class="button" />';
        echo $metabox_content;

        $images = unserialize($value);

        $script = "<script>
            itemsCount= 0;";
        if (!empty($images))
        {
            foreach ($images as $image)
            {
                $script.="addRow('{$image}');";
            }
        }
        $script .="</script>";
        echo $script;
    }

    function enqueue_scripts($hook)
    {
        if ('post.php' != $hook && 'post-edit.php' != $hook && 'post-new.php' != $hook)
            return;
        wp_enqueue_script('banner_uploader',  get_template_directory_uri()."/js/banner_uploader.js", array('jquery'));
    }

}


//***************************** END banner images metabox in page page ***********************

我在站点中找到了该代码,并对其进行了一些修改

//***************************** Start banner images metabox in page page ***********************



function call_Multi_Image_Uploader()
{
    new Multi_Image_Uploader();
}
function get_images($post_id=null)
{
    global $post;

    if ($post_id == null)
    {
        $post_id = $post->ID;
    }

    $value = get_post_meta($post_id, 'images', true);
    $images = unserialize($value);
    $result = array();
    if (!empty($images))
    {
        foreach ($images as $image)
        {
            $image = str_replace('.jpg', '-1903x428.jpg' , $image);
            $result[] = $image;
        }
    }
    return $result;
}

if (is_admin())
{
    add_action('load-post.php', 'call_Multi_Image_Uploader');
    add_action('load-post-new.php', 'call_Multi_Image_Uploader');
}
/**
 * Multi_Image_Uploader
 */
class Multi_Image_Uploader
{
    var $post_types = array();

    /**
     * Initialize Multi_Image_Uploader
     */
    public function __construct()
    {
        $this->post_types = array('page');     //limit meta box to certain post types
        add_action('add_meta_boxes', array($this, 'add_meta_box'));
        add_action('save_post', array($this, 'save'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'));
    }

    /**
     * Adds the meta box container.
     */
    public function add_meta_box($post_type)
    {
        if (in_array($post_type, $this->post_types))
        {
            add_meta_box(
                    'multi_image_upload_meta_box'
                    , __('Banner Image Upload', 'textdomain')
                    , array($this, 'render_meta_box_content')
                    , $post_type
                    , 'advanced'
                    , 'high'
            );
        }
    }
    /**
     * Save the images when the post is saved.
     *
     * @param int $post_id The ID of the post being saved.
     */
    public function save($post_id)
    {    /*
         * We need to verify this came from the our screen and with proper authorization,
         * because save_post can be triggered at other times.
         */

        // Check if our nonce is set.
        if (!isset($_POST['inner_custom_box_nonce']))
            return $post_id;

        $nonce = $_POST['inner_custom_box_nonce'];

        // Verify that the nonce is valid.
        if (!wp_verify_nonce($nonce, 'inner_custom_box'))
            return $post_id;

        // If this is an autosave, our form has not been submitted,
        //     so we don't want to do anything.
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
            return $post_id;

        // Check the user's permissions.
        if ('page' == $_POST['post_type'])
        {
            if (!current_user_can('edit_page', $post_id))
                return $post_id;
        } else
        {
            if (!current_user_can('edit_post', $post_id))
                return $post_id;
        }

        /* OK, its safe for us to save the data now. */
        // Validate user input.
        $posted_images = $_POST['images'];
        $images = array();
        if (!empty($posted_images))
        {
            foreach ($posted_images as $image_url)
            {
                if (!empty($image_url))
                    $images[] = esc_url_raw($image_url);
            }
        }

        // Update the images meta field.
        update_post_meta($post_id, 'images', serialize($images));
    }

    /**
     * Render Meta Box content.
     *
     * @param WP_Post $post The post object.
     */
    public function render_meta_box_content($post)
    {

        // Add an nonce field so we can check for it later.
        wp_nonce_field('inner_custom_box', 'inner_custom_box_nonce');

        // Use get_post_meta to retrieve an existing value from the database.
        $value = get_post_meta($post->ID, 'images', true);

        $metabox_content = '<div id="images"></div><input type="button" onClick="addRow()" value="Add Image" class="button" />';
        echo $metabox_content;

        $images = unserialize($value);

        $script = "<script>
            itemsCount= 0;";
        if (!empty($images))
        {
            foreach ($images as $image)
            {
                $script.="addRow('{$image}');";
            }
        }
        $script .="</script>";
        echo $script;
    }

    function enqueue_scripts($hook)
    {
        if ('post.php' != $hook && 'post-edit.php' != $hook && 'post-new.php' != $hook)
            return;
        wp_enqueue_script('banner_uploader',  get_template_directory_uri()."/js/banner_uploader.js", array('jquery'));
    }

}


//***************************** END banner images metabox in page page ***********************

我知道你并没有要求一个插件,但对于多个图像上传,我偶然发现这个免费插件,适合所有需要:。只需将此gallery字段添加到所需的帖子类型,即可轻松附加任意数量的图像。此外,只需几行代码即可获取图像。

我知道您没有要求使用插件,但对于多个图像上载,我偶然发现了这个适合所有需要的免费插件:。只需将此gallery字段添加到所需的帖子类型,即可轻松附加任意数量的图像。此外,只需几行代码即可获取图像。

这是我的工作解决方案,我使用基本的HTML多重上传表单,您只需对$u文件进行不同的处理,您可以在这里找到

这样,您将为上载的每个图像生成不同的元数据,现在您需要做的下一件事是正确设置metabox回调,输入字段应如下所示:

<input type="file" id="order_invoice_attachment" name="order_invoice[]" value="" size="25" multiple/>

然后你需要正确地显示文件,我会让你来决定,但是通过这个实现,文件会正确地保存为订单上的元数据字段。

这是我的工作解决方案,我使用基本的HTML多重上传表单,你只需要对$u文件进行不同的处理,在这里你可以找到

这样,您将为上载的每个图像生成不同的元数据,现在您需要做的下一件事是正确设置metabox回调,输入字段应如下所示:

<input type="file" id="order_invoice_attachment" name="order_invoice[]" value="" size="25" multiple/>

然后你需要正确地显示文件,我会让你决定,但是通过这个实现,文件会正确地保存为订单上的元数据字段。

谢谢你的回答,但这是一个插件,我创建了我的代码,但它给了我自己的上传图像。我搜索如何使用我的代码进行多次上传。这本质上是一个广告。谢谢你的回答,但这是一个插件,我创建了我的代码,但它给了我自己的上传图像。我搜索如何使用我的代码进行多次上传。这本质上是一个广告。我看到带有“添加图像”按钮的元框,但仅此而已,当我按下此按钮时,不会发生任何事情。抱歉,给您带来不便。按下按钮后,如果您有任何问题,请与我们分享?请将所有受尊敬的js添加到适当的工作中不,我什么都没有,可能是Javascript,但我看到一个js文件,它是banner_upload,那么从哪里获得它?!它不在metabox中,我在google中看不到它!所以在哪里可以找到它谢谢@Nisarg Thakkar如何在模板文件中显示与此一起上载的图像。后端工作正常。但在前端,我正在努力。addRow未定义我看到带有“添加图像”按钮的元框,但仅此而已,当我按下此按钮时,什么也没有发生对不起,给您带来不便。按下按钮后,如果您有任何问题,请与我们分享?请将所有受尊敬的js添加到适当的工作中不,我什么都没有,可能是Javascript,但我看到一个js文件,它是banner_upload,那么从哪里获得它?!它不在metabox中,我在google中看不到它!所以在哪里可以找到它谢谢@Nisarg Thakkar如何在模板文件中显示与此一起上载的图像。后端工作正常。但在前端我很挣扎。addRow没有定义